package com.boot.web.controller.weChat.api;

import com.aliyuncs.exceptions.ClientException;
import com.boot.constant.Constants;
import com.boot.communal.paging.InitPaging;
import com.boot.frame.qiniu.QiNiuConst;
import com.boot.frame.redis.JedisOperate;
import com.boot.communal.response.ResponseServer;
import com.boot.utils.*;
import com.boot.web.dao.*;
import com.boot.web.dto.*;
import com.boot.web.entity.*;
import com.boot.web.service.CustomerService;
import com.boot.web.service.OrdersCopyService;
import com.boot.web.service.OrdersService;
import com.boot.web.vo.*;
import com.github.binarywang.java.emoji.EmojiConverter;
import com.github.pagehelper.PageInfo;
import net.sf.json.JSONObject;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpMethod;
import org.springframework.http.ResponseEntity;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;
import org.springframework.util.ResourceUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.client.RestTemplate;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.math.BigDecimal;
import java.net.URLDecoder;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * 微信小程序API
 */
@RestController
@RequestMapping("/weChat")
public class WeChatApiController {

    @Autowired
    private BuyBlindBoxDao buyBlindBoxDao;

    @Autowired
    private CollageModeDao collageModeDao;

    @Autowired
    private ProductDao productDao;

    @Autowired
    private OrdersService ordersService;

    @Autowired
    private CouponDao couponDao;

    @Autowired
    private CustomerDao customerDao;

    @Autowired
    private AccountDao accountDao;

    @Autowired
    private OrdersDao ordersDao;

    @Autowired
    private AddressDao addressDao;

    @Autowired
    private OrderDetailsDao orderDetailsDao;

    @Autowired
    private StoreShopDao storeShopDao;

    @Autowired
    private ClassifyDao classifyDao;

    @Autowired
    private SkuRelationDao skuRelationDao;

    @Autowired
    private SpecAttributeDao specAttributeDao;

    @Autowired
    private CollageListDao collageListDao;

    @Autowired
    private BlindBoxDao blindBoxDao;

    @Autowired
    private CollageInRecord3Dao collageInRecord3Dao;

    @Autowired
    private ModeProductGameDao modeProductGameDao;

    @Autowired
    private CollageUserGameDao collageUserGameDao;

    @Autowired
    private PrizePoolDao prizePoolDao;

    @Autowired
    private OpenRedPackDao openRedPackDao;

    @Autowired
    private CustomerService customerService;

    @Autowired
    private AccountRecordDao accountRecordDao;

    @Autowired
    private  FailRedPackDao failRedPackDao;

    @Autowired
    private UserCouponDao userCouponDao;

    @Autowired
    private CollageInRecord2Dao collageInRecord2Dao;

    @Autowired
    private CollageInRecord3CopyDao collageInRecord3CopyDao;

    @Autowired
    private CollageInRecord20Dao collageInRecord20Dao;

    @Autowired
    private WinLoseRecordDao winLoseRecordDao;

    @Autowired
    private SkuSelectedDao skuSelectedDao;

    @Autowired
    private ModeProductDao modeProductDao;

    @Autowired
    private CollageUserDao collageUserDao;

    @Autowired
    private OrdersCopyDao ordersCopyDao;

    @Autowired
    private LevelDao levelDao;

    @Autowired
    private LevelCopyDao levelCopyDao;

    @Autowired
    private LevelCopy1Dao levelCopy1Dao;

    @Autowired
    private LevelCopy2Dao levelCopy2Dao;

    @Autowired
    private ArticleDao articleDao;

    @Autowired
    private ActivityDao activityDao;

    @Autowired
    private UserCardDao userCardDao;

    @Autowired
    private CardWithdrawalDao cardWithdrawalDao;

    @Autowired
    private OrdersCopyService ordersCopyService;

    @Autowired
    private SignInDao signInDao;

    @Autowired
    private SignInCopyDao signInCopyDao;


    /**
     * 加载盲盒数据
     * @param collageModeId
     * @return
     */
    @GetMapping("/getBlindBoxData")
    public ResponseServer getBlindBoxData(Integer collageModeId){
        CollageMode collageMode = collageModeDao.queryById(collageModeId);
        if(collageMode == null){
            return ResponseServer.error("数据加载失败，请重试");
        }
        if("".equals(collageMode.getIsShelf())){
            return ResponseServer.error(collageMode.getName() + "还未开启");
        }
        Map map = new HashMap();
        map.put("modeId", collageMode.getId());
        map.put("modeName", collageMode.getName());
        map.put("buyPrice", collageMode.getBuyPrice());
        map.put("modeImg", collageMode.getImg());
        List<BlindBoxStatusDTO> dtoList = new ArrayList<>();
        CollageList collageList = collageListDao.queryByModeId(collageModeId);
        List<BuyBlindBox> buyBlindBoxList = buyBlindBoxDao.queryBuyBlindBoxByModeId(collageList.getId());
        if(buyBlindBoxList.size() > 0){
            for(int i = 0; i < buyBlindBoxList.size(); i++){
                BuyBlindBox buyBlindBox = buyBlindBoxList.get(i);
                BlindBoxStatusDTO dto = new BlindBoxStatusDTO();
                dto.setId(String.valueOf(i));
                if(buyBlindBox.getUserId() != null){
                    dto.setSelected(true);
                }else{
                    dto.setSelected(false);
                }
                dtoList.add(dto);
            }
        }else{
            return ResponseServer.error(collageMode.getName() + "还未配置");
        }
        map.put("blindBoxStatus", dtoList);
        //List<ProductVO> voList = productDao.queryAllBlindBoxProduct();
        //map.put("blindBoxProduct", voList);
        return ResponseServer.success("加载成功", map);
    }


    /**
     * 加载盲盒数据 - 奖品信息
     * @return
     */
    @GetMapping("/getBlindBoxData_product")
    public ResponseServer getBlindBoxData_product(){
        CollageMode cm = collageModeDao.queryById(10);
        List<ProductVO> voList;
        if("1".equals(cm.getSuibian())){
            voList = productDao.queryAllBlindBoxProduct_1();
        }else{
            voList = productDao.queryAllBlindBoxProduct();
        }
        return ResponseServer.success("加载成功", voList);
    }


    /**
     * 加载盲盒数据 - 等待开奖
     * @param collageModeId
     * @return
     */
    @GetMapping("/getBlindBoxData1")
    public ResponseServer getBlindBoxData1(Integer collageModeId){
        CollageMode collageMode = collageModeDao.queryById(collageModeId);
        if(collageMode == null){
            return ResponseServer.error("数据加载失败，请重试");
        }
        if("0".equals(collageMode.getIsShelf())){
            return ResponseServer.error(collageMode.getName() + "还未开启");
        }
        List<BlindBoxStatusDTO> dtoList = new ArrayList<>();
        CollageList collageList = collageListDao.queryByModeId(collageModeId);
        List<BuyBlindBox> buyBlindBoxList = buyBlindBoxDao.queryBuyBlindBoxByModeId(collageList.getId());
        if(buyBlindBoxList.size() > 0){
            for(int i = 0; i < buyBlindBoxList.size(); i++){
                BuyBlindBox buyBlindBox = buyBlindBoxList.get(i);
                BlindBoxStatusDTO dto = new BlindBoxStatusDTO();
                dto.setId(String.valueOf(i));
                if(buyBlindBox.getUserId() != null){
                    dto.setSelected(true);
                }else{
                    dto.setSelected(false);
                }
                dtoList.add(dto);
            }
        }else{
            return ResponseServer.error(collageMode.getName() + "还未配置");
        }
        return ResponseServer.success("加载成功", dtoList);
    }


    /**
     * 加载盲盒数据 - 查看开奖
     * @param collageListId
     * @param userId
     * @return
     */
    @GetMapping("/getBlindBoxData2")
    public ResponseServer getBlindBoxData2(Integer collageListId, Integer userId) {
        Map map = new HashMap();
        List<BuyBlindBoxStatusDTO> dtoList = new ArrayList<>();
        CollageList collageList = collageListDao.queryById(collageListId);
        List<BuyBlindBox> buyBlindBoxList = buyBlindBoxDao.queryBuyBlindBoxByModeId(collageList.getId());
        if (buyBlindBoxList.size() > 0) {
            for (int i = 0; i < buyBlindBoxList.size(); i++) {
                BuyBlindBox buyBlindBox = buyBlindBoxList.get(i);
                BuyBlindBoxStatusDTO dto = new BuyBlindBoxStatusDTO();
                dto.setId(String.valueOf(i));
                dto.setHeadImg(customerDao.queryById(buyBlindBox.getUserId()).getHeadImg());
                dtoList.add(dto);
            }
        }
        map.put("BuyBlindBoxStatusDTO", dtoList);
        Customer customer = customerDao.queryById(userId);
        map.put("nickName", customer.getNickName());
        map.put("headImg", customer.getHeadImg());
        Orders orders = ordersDao.queryByIds(collageListId, userId);
        OrderDetails od = orderDetailsDao.queryByOrderNo(orders.getOrderNo());
        map.put("productImg", od.getProductImg());
        map.put("productName", od.getProductName());
        return ResponseServer.success("加载成功", map);
    }


    /**
     * 加载产品详情数据
     * @param productId
     * @return
     */
    @GetMapping("/getProductDetailsData")
    public ResponseServer getProductDetailsData(Integer productId){
        ProductVO vo = productDao.queryProductById(productId);
        if(vo.getBannerImg().length() > 0){
            List list = new ArrayList();
            if(vo.getBannerImg().contains(";")){
                String[] strings = vo.getBannerImg().split(";");
                for(int i = 0; i < strings.length; i++){
                    list.add(strings[i]);
                }
            }else{
                list.add(vo.getBannerImg());
            }
            vo.setBannerImgList(list);
        }
        if(vo.getDetailsImg().length() > 0){
            List list1 = new ArrayList();
            if(vo.getDetailsImg().contains(";")){
                String[] strings1 = vo.getDetailsImg().split(";");
                for(int y = 0; y < strings1.length; y++){
                    list1.add(strings1[y]);
                }
            }else{
                list1.add(vo.getDetailsImg());
            }
            vo.setDetailsImgList(list1);
        }
        List<SkuRelation> skuList = skuRelationDao.queryByProductId(productId);
        SkuRelation sku = skuList.get(0);
        vo.setSkuId(sku.getId());
        vo.setRetailPrice(sku.getRetailPrice());
        if(sku.getGroupRelation().contains(",")){
            String[] strings = sku.getGroupRelation().split(",");
            String str = "";
            for(int u = 0; u < strings.length; u++){
                str += specAttributeDao.queryById(Integer.parseInt(strings[u])).getAttributeName() + "，";
            }
            vo.setSpecAttributeName(str.substring(0, str.length()-1));
        }else{
            vo.setSpecAttributeName(specAttributeDao.queryById(Integer.parseInt(sku.getGroupRelation())).getAttributeName());
        }
        vo.setQuantity(1);
        return ResponseServer.success("加载成功", vo);
    }


    /**
     * 加载登录人已邀请的人员信息，同时实现搜索
     * @param userId
     * @param agentCode
     * @return
     */
    @GetMapping("/getInvitationList")
    public ResponseServer getInvitationList(Integer userId, String agentCode){
        Map map = new HashMap();
        Customer customer = customerDao.queryById(userId);
        CustomerVO1 parent = customerDao.queryById1(customer.getParentId());
        map.put("parentCustomer", parent);
        List<CustomerVO1> voList = customerDao.queryByParentId(userId);
        map.put("customerList", voList);
        if(agentCode != null && !"".equals(agentCode)){
            CustomerVO1 queryCustomer = customerDao.queryById2(agentCode);
            map.put("queryCustomer", queryCustomer);
        }
        return ResponseServer.success("加载成功", map);
    }


    /**
     * 加载正在进行中的盲盒信息
     * @return
     */
    @GetMapping("/getBlindBoxIng")
    public ResponseServer getBlindBoxIng(){
        CollageList collageList = collageListDao.queryCollageListByStatus0();
        if(collageList != null){
            CollageMode collageMode = collageModeDao.queryById(collageList.getCollageModeId());
            return ResponseServer.success("加载成功", collageMode);
        }
        return ResponseServer.error("没有正在进行中的盲盒");
    }


    /**
     * 小程序登录
     *
     * @param encryptedData
     * @param iv
     * @param code
     * @return
     */
    @GetMapping("/login")
    public ResponseServer login(@RequestParam(value = "encryptedData", required = false) String encryptedData,
                                  @RequestParam(value = "iv", required = false) String iv,
                                  @RequestParam(value = "code", required = false) String code,
                                  @RequestParam(value = "parentid", required = false) int parentid,
                                  @RequestParam(value = "nickName", required = false) String nickName,
                                  @RequestParam(value = "city", required = false) String city,
                                  @RequestParam(value = "avatarUrl", required = false) String avatarUrl,
                                  HttpServletRequest request) {
        Map map = new HashMap();
        System.err.println("小程序传过来数据---");
        System.err.println("encryptedData:=====>" + encryptedData);
        System.err.println("iv:=====>" + iv);
        System.err.println("code:=====>" + code);
        System.err.println("parentid:=====>" + parentid);
        System.err.println("nickName:=====>" + nickName);
        System.err.println("city:=====>" + city);
        System.err.println("avatarUrl:=====>" + avatarUrl);

        // 小程序唯一标识 (在微信小程序管理后台获取)
        String wxAppId = Constants.wxAppId;
        // 小程序的 app secret (在微信小程序管理后台获取)
        String wxAppSecret = Constants.wxAppSecret;
        // 授权（必填）
        String grant_type = "authorization_code";
        /// 1、向微信服务器 使用登录凭证 code 获取 session_key 和 openid
        // 请求参数
        String params = "appid=" + wxAppId + "&secret=" + wxAppSecret + "&js_code=" + code + "&grant_type="
                + grant_type;
        // 发送请求
        String sr = HttpRequestUtil.sendGet("https://api.weixin.qq.com/sns/jscode2session", params);
        // 解析相应内容（转换成json对象）
        JSONObject json = JSONObject.fromObject(sr);
        System.err.println("登录返回所有数据-----" + json);
        // 获取会话密钥（session_key）
        String session_key = json.get("session_key").toString();
        // 用户的唯一标识（openid）
        String openId = (String) json.get("openid");
        String unionId = (String) json.get("unionid");
        System.err.println("登录返回数据unionId-----" + unionId);
        Customer customer = customerDao.queryCustomerByUnionId(unionId);
        String user_unionId = null;
        if (unionId == null || unionId == "") {
            try {
                String result = AesCbcUtil.getUserInfo(encryptedData, session_key, iv);
                // 用户所有数据-------------------
                JSONObject userInfoJSON = JSONObject.fromObject(result);
                System.err.println("微信openId---" + userInfoJSON.get("openId").toString());// 微信微信唯一id
                System.err.println("昵称-----------" + userInfoJSON.get("nickName").toString());// 昵称
                System.err.println("登录城市--------" + userInfoJSON.get("city").toString());// 登陆城市
                System.err.println("用户头像--------" + userInfoJSON.get("avatarUrl").toString());// 用户头像
                System.err.println("微信unionId--------" + userInfoJSON.get("unionId").toString());// 用户unionId
                // 用户的唯一标识（unionId）
                user_unionId = userInfoJSON.get("unionId").toString();
                customer = customerDao.queryCustomerByUnionId(user_unionId);
            } catch (Exception e) {
                e.printStackTrace();
                return ResponseServer.error("获取用户信息错误");
            }
            if (user_unionId != null && user_unionId != "") {
                unionId = user_unionId;
            }
        }
        //String content = "xF0\x9F\x98\x82\xF0\x9F";
        EmojiConverter emojiConverter = EmojiConverter.getInstance();
        //content= emojiConverter.toAlias(content);
        nickName = emojiConverter.toAlias(nickName);
        Integer userId = null;
        //TODO 判断用户是否存在
        if (customer == null && unionId != null && unionId != "") {
            Customer newCustomer = new Customer();
            newCustomer.setUpdateTime(new Date());
            newCustomer.setIsDel("0");
            // 全部为游客
            newCustomer.setLevelId(1);
            newCustomer.setLevelCopyId(1);
            newCustomer.setLevelCopy1Id(1);
            newCustomer.setLevelCopy2Id(1);
            newCustomer.setLevelCopy3Id(1);
            newCustomer.setLevelCopy4Id(1);
            // 全部未激活
            newCustomer.setIsActive("0");
            newCustomer.setIsActiveCopy("0");
            newCustomer.setIsActiveCopy1("0");
            newCustomer.setIsActiveCopy2("0");
            newCustomer.setIsActiveCopy3("0");
            newCustomer.setIsActiveCopy4("1");
            newCustomer.setHeadImg(avatarUrl);
            newCustomer.setNickName(nickName);
            newCustomer.setOpenId(openId);
            newCustomer.setUnionId(unionId);
            if (parentid != 1198) {
                Customer p = customerDao.queryById(parentid);
                if(p == null){
                    return ResponseServer.error("上级ID不存在");
                }
                if(p.getAgentCode() != null && !"".equals(p.getAgentCode())){
                    String str = p.getAgentCode().substring(0,3);
                    String newCode;
                    do {
                        newCode = str + randoms();
                        if (customerDao.queryCustomerByAgentCode(newCode) == null) {
                            break;
                        }
                    } while (customerDao.queryCustomerByAgentCode(newCode) != null);
                    newCustomer.setAgentCode(newCode);
                    newCustomer.setParentId(parentid);
                    //newCustomer.setSign(String.valueOf(parentid));
                }else{
                    newCustomer.setAgentCode("");
                }
            } else {
                newCustomer.setParentId(1198);
            }
            BigDecimal decimal = new BigDecimal(0);
            newCustomer.setAchievement(decimal);
            newCustomer.setAchievement3(decimal);
            //newCustomer.setVerifyStatus("3");
            newCustomer.setQuantityRecord(0);
            newCustomer.setOwnTotalBuy(decimal);
            newCustomer.setOwnTotalBuy3(decimal);
            newCustomer.setFiction("0");
            newCustomer.setAddUpAchievement(decimal);
            newCustomer.setAddUpUpgrade(decimal);
            newCustomer.setAddUpUpgradeFiction(decimal);
            newCustomer.setVerifyStatus("3");
            newCustomer.setEffective(0);
            newCustomer.setOrderQuantity(0);
            newCustomer.setIsMember("1"); // 全部默认为会员
            newCustomer.setIsDel("0");
            newCustomer.setRepeatAmount(new BigDecimal(0));
            newCustomer.setTodayArean(new BigDecimal(0));
            customerDao.save(newCustomer);
            userId = newCustomer.getId();
            if(accountDao.queryAccountByUserId(newCustomer.getId()) == null){
                Account account = new Account();
                account.setIntegral(0);
                account.setBliss(0);
                account.setRedPacket(0);
                account.setVoucherBalance(decimal);
                account.setUpdateTime(new Date());
                account.setUserId(newCustomer.getId());
                account.setCollageBalance(decimal);
                account.setShareBalance(decimal);
                account.setFrozenIn(decimal);
                accountDao.save(account);
                List<Coupon> couponList = couponDao.queryAll();
                if(couponList.size() > 0){
                    for(Coupon cou : couponList){
                        UserCoupon uc = userCouponDao.queryByUserIdAndCouponId(newCustomer.getId(), cou.getId());
                        if(uc == null){
                            UserCoupon newUc= new UserCoupon();
                            newUc.setCouponId(cou.getId());
                            newUc.setUserId(newCustomer.getId());
                            newUc.setUpdateTime(new Date());
                            newUc.setQuantity(0);
                            userCouponDao.save(newUc);
                        }
                    }
                }
            }
        } else {
            if (!customer.getHeadImg().equals(avatarUrl) || !customer.getNickName().equals(nickName)
                    || customer.getOpenId() == null || !customer.getOpenId().equals(openId)
                    || customer.getParentId() == 1198 || customer.getAgentCode() == null) {
                Customer oldCustomer = new Customer();
                oldCustomer.setOpenId(openId);
                oldCustomer.setNickName(nickName);
                oldCustomer.setHeadImg(avatarUrl);
                oldCustomer.setUpdateTime(new Date());
                oldCustomer.setId(customer.getId());
                if (customer.getParentId() == 1198 && parentid != 1198 && customer.getId() != parentid) {
                    Customer p = customerDao.queryById(parentid);
                    if(p == null){
                        return ResponseServer.error("上级ID不存在");
                    }
                    if(p.getAgentCode() != null && !"".equals(p.getAgentCode())){
                        String str = p.getAgentCode().substring(0,3);
                        String newCode;
                        do {
                            newCode = str + randoms();
                            if (customerDao.queryCustomerByAgentCode(newCode) == null) {
                                break;
                            }
                        } while (customerDao.queryCustomerByAgentCode(newCode) != null);
                        oldCustomer.setAgentCode(newCode);
                        oldCustomer.setParentId(parentid);
                    }else{
                        oldCustomer.setAgentCode("");
                    }
                }
                if (customer.getParentId() != 1198 && (customer.getAgentCode() == null || customer.getAgentCode() == "")) {
                    Customer p = customerDao.queryById(parentid);
                    if(p == null){
                        return ResponseServer.error("上级ID不存在");
                    }
                    if(p.getAgentCode() != null && !"".equals(p.getAgentCode())){
                        String str = p.getAgentCode().substring(0,3);
                        String newCode;
                        do {
                            newCode = str + randoms();
                            if (customerDao.queryCustomerByAgentCode(newCode) == null) {
                                break;
                            }
                        } while (customerDao.queryCustomerByAgentCode(newCode) != null);
                        oldCustomer.setAgentCode(newCode);
                        oldCustomer.setParentId(parentid);
                    }else{
                        oldCustomer.setAgentCode("");
                    }
                }
                customerDao.update(oldCustomer);
                userId = oldCustomer.getId();
            }else{
                userId = customer.getId();
            }
        }
        Customer user = customerDao.queryById(userId);
        map.put("userids", userId);
        map.put("openid", user.getOpenId());
        map.put("session_key", session_key);
        map.put("unionid", user.getUnionId());
        map.put("phone", user.getMobile());
        return ResponseServer.success(map);
    }


    /**
     * 通过openid获取微信用户信息
     * @param openid
     * @return
     */
    @GetMapping("/getUserInfoByOpenid")
    public ResponseServer getUserInfoByOpenid(String openid) {
        if (openid != null && openid != "") {
            Customer user = customerDao.queryCustomerByOpenId(openid);
            return ResponseServer.success(user);
        } else {
            return ResponseServer.error("openId不存在");
        }
    }


    /**
     * 校验手机号并获取短信验证码
     * @param userId
     * @param phone
     * @return
     */
    @GetMapping("/verifyPhoneGetCode")
    public ResponseServer verifyPhoneGetCode(Integer userId, String phone) throws ClientException {
        //Customer customer = customerDao.queryCustomerByMobile(phone);
        //if(customer != null){
            //return ResponseServer.error("手机号码已存在");
        //}else{
            Customer cu = customerDao.queryById(userId);
            if(cu != null){
                // 发送验证码并保存
                RandomNumberUtil rn = new RandomNumberUtil();
                String code = rn.verificationCode();
                //Jedis jedis = new Jedis("localhost");
                //jedis.set(phone, code);
                JedisOperate.setObject(phone, code, 120);
                SendSmsUtil.sendSms(phone, code);
                return ResponseServer.success("短信验证码发送成功!");
            }
        //}
        return ResponseServer.error("短信验证码发送失败，请重试!");
    }


    /**
     * 绑定手机号
     * @param userId
     * @param phone
     * @param code
     * @return
     */
    @GetMapping("/bindPhone")
    public ResponseServer bindPhone(Integer userId, String phone, String code) throws IOException {
        Customer customer = customerDao.queryCustomerByMobile(phone);
        if(customer != null){
            return ResponseServer.error("手机号码已存在");
        }else{
            Customer cu = customerDao.queryById(userId);
            if(cu != null){
                //Jedis jedis = new Jedis("localhost");
                //String checkCode = jedis.get(phone);
                String checkCode = JedisOperate.getObject(phone).toString();
                if (code.equals(checkCode)) {
                    cu.setMobile(phone);
                    cu.setPassword(phone);
                    customerDao.update(cu);
                    return ResponseServer.success("绑定手机号码成功");
                }else{
                    return ResponseServer.error("短信验证码错误");
                }
            }
        }
        return ResponseServer.error("登录信息不正确，请重试!");
    }


    /**
     * 用户userId查询
     * @param open_id
     * @return
     */
    @GetMapping("/getUserInfoById")
    public ResponseServer getUserInfoById(@RequestParam(required = false) Integer open_id) {
        Map map = new HashMap();
        try {
            Customer user = customerDao.queryById(open_id);
            if (user != null) {
                map.put("fopenid", user.getOpenId());
                map.put("userId", user.getId());
            }
            return ResponseServer.success(map);
        } catch (Exception e) {
            e.printStackTrace();
            return ResponseServer.error("用户ID不存在");
        }

    }


    public static int randoms() {
        int j = (int)((Math.random()*9+1)*100000);
        return j;
    }


    /**
     * 登录成功后加载客户数据
     * @param userId
     * @return
     */
    @GetMapping("/getCustomerInfoData")
    public ResponseServer getCustomerInfoData(Integer userId){
        CustomerDTO dto = new CustomerDTO();
        CustomerVO vo = customerDao.queryCustomerVOById(userId);
        BeanUtils.copyProperties(vo, dto);
        dto.setParentCount(customerDao.queryCustomerByParentId(userId).size());

        dto.setWaitingCount(ordersDao.queryOrdersVOByStatus(userId, "5").size()); //等开奖

        dto.setDeliveredCount(ordersDao.queryOrdersVOByStatus(userId, "1").size()); //待发货

        dto.setReceivedCount(ordersDao.queryOrdersVOByStatus(userId, "2").size()); //待收货

        dto.setAfterSalesCount(ordersDao.queryOrdersVOByStatus(userId, "7").size()); //代售

        dto.setCollageCount(ordersDao.queryOrdersVOByStatus(userId, "6").size()); //待开团

        return ResponseServer.success("加载成功", dto);
    }


    /**
     * 加载客户地址数据
     * @param userId
     * @return
     */
    @GetMapping("/getAddressData")
    public ResponseServer getAddressData(Integer userId){
        return ResponseServer.success("加载成功", addressDao.queryAllAddressVOByUserId(userId));
    }


    /**
     * 判断是否购买过当前团盲盒
     * @param userId
     * @return
     */
    @GetMapping("/judgeIsBuyBox")
    public ResponseServer judgeIsBuyBox(Integer collageModeId, Integer userId){
        //CollageList collageList = collageListDao.queryByModeId(collageModeId);
        //BuyBlindBox buyBlindBox = buyBlindBoxDao.queryBuyBlindBoxByUserId2(collageList.getId(), userId);
        //if(buyBlindBox == null){
            //return ResponseServer.success("没有购买过");
        //}else{
            // return ResponseServer.error("购买过");
            // TODO 将代码调整为一个人可以多次购买
            return ResponseServer.success("没有购买过");
        //}
    }


    /**
     * 添加或修改地址
     * @param address
     * @param userId
     * @return
     */
    @PostMapping("/address/saveOrUpdate")
    public ResponseServer saveAddress(Address address, Integer userId){
        address.setUpdateTime(new Date());
        if(address.getIsDefault().equals("1")) {
            Address updateIdentity = addressDao.findAddressByIsDefault(userId, address.getIsDefault());
            if (updateIdentity != null) {
                updateIdentity.setIsDefault("0");
                addressDao.update(updateIdentity);
            }
        }
        address.setUserId(userId);
        //address.setFullAddress(address.getProvince() + address.getCity() + address.getCounty() + address.getAddress());
        if(address.getProvince().contains("甘肃") || address.getProvince().contains("新疆") || address.getProvince().contains("内蒙古") ||
                address.getProvince().contains("宁夏") || address.getProvince().contains("青海") || address.getProvince().contains("西藏")){
            address.setFreight(String.valueOf(10));
        }else{
            address.setFreight(String.valueOf(0));
        }
        if(address.getId() == null){
            addressDao.save(address);
            return ResponseServer.success("地址修改成功");
        }else{
            addressDao.update(address);
            return ResponseServer.success("地址添加成功");
        }
    }


    /**
     * 根据ID删除地址
     * @param addressId
     * @return
     */
    @PostMapping("/address/delete")
    public ResponseServer deleteAddress(Integer addressId){
        addressDao.delete(addressId);
        return ResponseServer.success("删除成功");
    }


    /**
     * 加载客户订单数据
     * @param userId
     * @param status
     * @return
     */
    @GetMapping("/getOrdersData")
    public ResponseServer getOrdersData(Integer userId, String status){
        return ResponseServer.success("加载成功", ordersDao.queryOrdersVOByStatus(userId, status));
    }


    /**
     * 订单详情数据
     * @param orderNo
     * @return
     */
    @GetMapping("/getOrdersDetailsData")
    public ResponseServer getOrdersDetailsData(String orderNo){
        OrdersVO ordersVO = ordersDao.queryOrdersVOByOrderNo(orderNo);
        return ResponseServer.success("加载成功", ordersVO);
    }


    /**
     * 购买盲盒获取产品自定义参数
     * @param modeId
     * @return
     */
    @GetMapping("/getBuyBlindBoxData")
    public ResponseServer getBuyBlindBoxData(Integer modeId){
        CollageMode collageMode = collageModeDao.queryById(modeId);
        BuyBlindBoxDTO dto = new BuyBlindBoxDTO();
        dto.setProImg("https://ceshi.jiajiani.cn/img/upload/mifeng.png");
        dto.setProNum(1);
        dto.setProTitle(collageMode.getName());
        dto.setUnitPrice(collageMode.getBuyPrice());
        dto.setSpecsTxt("随机");
        List<BuyBlindBoxDTO> dtoList = new ArrayList<>();
        dtoList.add(dto);
        return ResponseServer.success("加载成功", dtoList);
    }


    /**
     * 积分兑换产品获取产品自定义参数
     * @param productId
     * @return
     */
    @GetMapping("/getBuyBlindBoxData1")
    public ResponseServer getBuyBlindBoxData1(Integer productId){
        ProductVO vo = productDao.queryProductById(productId);
        List<SkuRelation> skuList = skuRelationDao.queryByProductId(productId);
        SkuRelation sku = skuList.get(0);
        if(sku.getGroupRelation().contains(",")){
            String[] strings = sku.getGroupRelation().split(",");
            String str = "";
            for(int u = 0; u < strings.length; u++){
                str += specAttributeDao.queryById(Integer.parseInt(strings[u])).getAttributeName() + "，";
            }
            vo.setSpecAttributeName(str.substring(0, str.length()-1));
        }else{
            vo.setSpecAttributeName(specAttributeDao.queryById(Integer.parseInt(sku.getGroupRelation())).getAttributeName());
        }
        List<StoreShopFreightVO> voList = storeShopFreightDao.queryStoreShopFreightVOById(vo.getStoreShopId());
        vo.setStoreShopFreightVOList(voList);
        return ResponseServer.success("加载成功", vo);
    }


    /**
     * 购买礼包获取产品参数
     * @param productId
     * @return
     */
    @GetMapping("/getConfirmProductData")
    public ResponseServer getConfirmProductData(Integer productId){
        ConfirmProductDTO dto = productDao.queryProductById1(productId);
        List<SkuRelation> skuList = skuRelationDao.queryByProductId(productId);
        SkuRelation sku = skuList.get(0);
        dto.setSkuId(sku.getId());
        dto.setRetailPrice(sku.getRetailPrice());
        if(sku.getGroupRelation().contains(",")){
            String[] strings = sku.getGroupRelation().split(",");
            String str = "";
            for(int u = 0; u < strings.length; u++){
                str += specAttributeDao.queryById(Integer.parseInt(strings[u])).getAttributeName() + "，";
            }
            dto.setSpecAttributeName(str.substring(0, str.length()-1));
        }else{
            dto.setSpecAttributeName(specAttributeDao.queryById(Integer.parseInt(sku.getGroupRelation())).getAttributeName());
        }
        dto.setQuantity(1);
        return ResponseServer.success(dto);
    }


    /**
     * 购买盲盒，微信支付
     * @param request
     * @param modeId
     * @param openId
     * @param consigneeName
     * @param fullAddress
     * @param consigneePhone
     * @param userId
     * @param freight
     * @return
     */
    @PostMapping("/blindBox/pay")
    public ResponseServer blindBoxPay(HttpServletRequest request, @RequestParam(required = false) Integer modeId,
                                  @RequestParam(required = false) String openId,
                                  @RequestParam(required = false) String consigneeName,
                                  @RequestParam(required = false) String fullAddress,
                                  @RequestParam(required = false) String consigneePhone,
                                  @RequestParam(required = false) Integer userId,
                                  @RequestParam(required = false) BigDecimal freight) throws Exception {

        System.err.println("-------------创建订单传递的参数：modeId= " + modeId);
        System.err.println("-------------创建订单传递的参数：openId= " + openId);
        System.err.println("-------------创建订单传递的参数：consigneeName= " + consigneeName);
        System.err.println("-------------创建订单传递的参数：fullAddress= " + fullAddress);
        System.err.println("-------------创建订单传递的参数：consigneePhone= " + consigneePhone);
        System.err.println("-------------创建订单传递的参数：userId= " + userId);
        System.err.println("-------------创建订单传递的参数：freight= " + freight);

        Map<String, String> maps = new HashMap<>();
        CollageMode collageMode = collageModeDao.queryById(modeId);
        BigDecimal totalPrice;
        // 商户订单号
        String outTradeNo = "BEE" + Units.getOrderIdByTime().replaceAll("-", "");
        // 交易号
        String tradeNo = "JYH" + Units.getOrderIdByTime().replaceAll("-", "");
        if (freight == null) {
            freight = BigDecimal.valueOf(0.0);
        }
        totalPrice = collageMode.getBuyPrice().add(freight);
        Map<String, String> map;
        if (totalPrice.doubleValue() > 0) {
            Map<String, Object> wxPay = new HashMap<>();
            wxPay.put("totalPrice", totalPrice.doubleValue());
            wxPay.put("outTradeNo", outTradeNo);
            wxPay.put("openId", openId);
            wxPay.put("notifyUrl", Constants.notify_url_adjust); // 调整盲盒 原：notify_url  现：notify_url_adjust
            wxPay.put("wxPayAppId", Constants.wxAppId);
            wxPay.put("tradeType", Constants.trade_type);
            String paramBuffer = CreateUnifiedOrder.UnifiedOrder(request, wxPay);
            map = Units.doXMLParse(HttpRequestUtil.sendPost(Constants.pay_url, new String(paramBuffer.getBytes(), "UTF-8")));
            // 创建订单
            if (map != null) {
                Orders orders = new Orders();
                orders.setOrderNo(outTradeNo);
                orders.setTradeNo(tradeNo);
                orders.setTotalAmount(totalPrice);
                orders.setPayAmount(totalPrice);
                orders.setCouponAmount(new BigDecimal(0));
                orders.setFreight(freight);
                orders.setPayStatus("0");
                orders.setPayType("0");
                orders.setDealStatus("0");
                orders.setRefundStatus("0");
                orders.setPrepayId(map.get("prepay_id"));
                CollageList collageList = collageListDao.queryByModeId(modeId); //获取正在进行的盲盒
                orders.setCollageListId(collageList.getId());
                orders.setCollageModeId(modeId);
                orders.setModeName(collageMode.getName());
                orders.setOrderPersonId(userId);
                orders.setConsigneeName(consigneeName);
                orders.setConsigneePhone(consigneePhone);
                orders.setAddress(fullAddress);
                orders.setUpdateTime(new Date());
                orders.setIsDel("1");
                orders.setIsRun("0");
                orders.setLastCollage("0");
                orders.setRemarks("无");
                ordersDao.save(orders);
                maps.put("prepayId", map.get("prepay_id"));
                maps.put("outTradeNo", outTradeNo);

                return ResponseServer.success(maps);
            }
        }
        maps.put("prepayId", "");
        maps.put("msg", "支付失败,请重试");
        return ResponseServer.success(maps);
    }


    /**
     * 生成 微信支付 签名后台
     *
     * @param prepayId
     * @return
     */
    @PostMapping("/generateSignature")
    public ResponseServer generateSignature(@RequestParam(required = false) String prepayId) {
        JSONObject resultJson;
        try {
            resultJson = CreateUnifiedOrder.generateSignature(prepayId, Constants.wxAppId);
        } catch (Exception e) {
            e.printStackTrace();
            return ResponseServer.error("生成微信支付签名失败");
        }
        return ResponseServer.success(resultJson);
    }


    /**
     * 盲盒未支付成功删除订单
     * @param orderNo
     * @return
     */
    @PostMapping("/delete/orders")
    public ResponseServer deleteOrders(String orderNo){
        Orders orders = ordersDao.queryByOrderNo(orderNo);
        ordersDao.delete(orders.getId());
        return ResponseServer.success();
    }


    /**
     * 礼包未支付成功删除订单
     * @param orderNo
     * @return
     */
    @PostMapping("/delete/orders/pack")
    public ResponseServer deleteOrdersPack(String orderNo){
        Orders orders = ordersDao.queryByOrderNo(orderNo);
        OrderDetails od = orderDetailsDao.queryByOrderNo(orderNo);

        if(orders.getCollageModeId() == null){

        }else{
            if(orders.getCollageModeId() == 5 || orders.getCollageModeId() == 6){
                // 处理拼团游戏产品取消支付后 把团也删了
                ModeProductGame mpg = modeProductGameDao.queryById(orders.getModeProductId());
                if(mpg != null){
                    CollageUserGame cug = collageUserGameDao.queryByModeId(mpg.getId());
                    if(cug != null){
                        collageUserGameDao.delete(cug.getId());
                    }
                    modeProductGameDao.delete(mpg.getId());
                }
            }
        }

        orderDetailsDao.delete(od.getId());
        ordersDao.delete(orders.getId());
        return ResponseServer.success();
    }


    /**
     * 取消订单
     * @param orderNo
     * @return
     */
    @PostMapping("/cancelOrders")
    public ResponseServer cancelOrders(String orderNo){
        Orders orders = ordersDao.queryByOrderNo(orderNo);
        orders.setIsDel("1");
        ordersDao.update(orders);
        return ResponseServer.success();
    }


    /**
     * 代售自提
     * @param orderNo
     * @return
     */
    @PostMapping("/pickedUp")
    public ResponseServer pickedUp(String orderNo){
        Orders orders = ordersDao.queryByOrderNo(orderNo);
        if(orders != null){
            CollageInRecord3 cir3 = collageInRecord3Dao.queryByOrderNo(orderNo);
            if(cir3 != null){
                if("0".equals(cir3.getStatus()) && "1".equals(cir3.getIsTake())){
                    cir3.setStatus("1");
                    cir3.setIsTake("0");
                    collageInRecord3Dao.update(cir3);

                    orders.setDealStatus("1");
                    ordersDao.update(orders);

                    return ResponseServer.success("自提成功");
                }
            }
            return ResponseServer.error("自提失败");
        }else{
            return ResponseServer.error("自提失败，请联系管理员");
        }
    }


    /**
     * 订单确定收货
     * @param orderNo
     * @return
     */
    @PostMapping("/confirmReceipt")
    public ResponseServer confirmReceipt(String orderNo){
        Orders orders = ordersDao.queryByOrderNo(orderNo);
        if("1".equals(orders.getPayStatus()) && "0".equals(orders.getRefundStatus()) && "2".equals(orders.getDealStatus())){
            orders.setDealStatus("3");
            orders.setConfirmTime(new Date());
            ordersDao.update(orders);
            return ResponseServer.success("确认收货成功");
        }else{
            return ResponseServer.error("确认收货失败，订单状态不正确");
        }
    }


    /**
     * 盲盒支付成功后回调
     * @param request
     * @param response
     */
    @PostMapping("/notify_url")
    public void blindBoxPayCallback(HttpServletRequest request, HttpServletResponse response) {
        System.err.println("微信回调接口方法 start ----------------------------");
        String inputLine = "";
        String notityXml = "";
        try {
            while ((inputLine = request.getReader().readLine()) != null) {
                notityXml += inputLine;
            }
            // 关闭流
            request.getReader().close();
            System.err.println("小程序商城支付回调：" + notityXml);
            // 解析成Map
            Map<String, String> map = Units.doXMLParse(notityXml);
            System.err.println(map);
            // 判断 支付是否成功
            if ("SUCCESS".equals(map.get("result_code"))) {
                System.err.println("微信回调返回是否支付成功：是");
                // 获得 返回的商户订单号
                String outTradeNo = map.get("out_trade_no");
                double totalFee = Double.parseDouble(map.get("total_fee")) / 100;
                System.err.println("微信回调返回商户订单号：" + outTradeNo);
                System.err.println("微信回调返回支付金额：" + totalFee);

                Orders orders = ordersDao.queryByOrderNo(outTradeNo);

                List<BuyBlindBox> buyList = buyBlindBoxDao.queryBuyBlindBoxByUserId1(orders.getCollageListId());
                int buySize = buyList.size();
                if(buySize > 0){
                    if(buySize == 1){
                        // 最后一个盲盒
                        BuyBlindBox buy = buyList.get(0);
                        buy.setUserId(orders.getOrderPersonId());
                        buyBlindBoxDao.update(buy);

                        // 随机产品
                        List<Product> productList = productDao.queryProductByClassifyId(buy.getClassifyId());
                        int productSize = productList.size();
                        int productRandom = 1 + (int)(Math.random()*(productSize + 1 - 1));
                        Product product = productList.get(productRandom-1);
                        product.setSales(product.getSales() + 1); // 添加销量
                        productDao.update(product);

                        OrderDetails od = new OrderDetails();
                        od.setOrderNo(orders.getOrderNo());
                        od.setTradeNo(orders.getTradeNo());
                        od.setStoreShopId(product.getStoreShopId());
                        od.setStoreShopName(storeShopDao.queryById(product.getStoreShopId()).getName());
                        od.setClassifyId(product.getClassifyId());
                        od.setClassifyName(classifyDao.queryById(product.getClassifyId()).getName());
                        od.setProductId(product.getId());
                        od.setProductType(product.getType());
                        od.setProductImg(product.getImg());
                        od.setProductName(product.getName());
                        List<SkuRelation> skuList = skuRelationDao.queryByProductId(product.getId());
                        SkuRelation sku = skuList.get(0);
                        od.setProductCode(product.getProductCode());
                        od.setCostPrice(sku.getCostPrice());
                        od.setRelationId(sku.getId());
                        if(sku.getGroupRelation().contains(",")){
                            String[] strings = sku.getGroupRelation().split(",");
                            String str = "";
                            for(int u = 0; u < strings.length; u++){
                                str += specAttributeDao.queryById(Integer.parseInt(strings[u])).getAttributeName() + "，";
                            }
                            od.setSpecAttributeName(str.substring(0, str.length()-1));
                        }else{
                            od.setSpecAttributeName(specAttributeDao.queryById(Integer.parseInt(sku.getGroupRelation())).getAttributeName());
                        }
                        od.setQuantity(1);
                        od.setUnitPrice(sku.getRetailPrice());
                        od.setUpdateTime(new Date());
                        orderDetailsDao.save(od);
                        // 修改订单状态
                        orders.setPayStatus("1");
                        orders.setDealStatus("5");
                        orders.setIsDel("0");
                        ordersDao.update(orders);

                        // 盲盒已抽完
                        CollageList collageList = collageListDao.queryById(orders.getCollageListId());
                        collageList.setStatus("1");
                        collageListDao.update(collageList);
                        // 重新生成盲盒
                        if(collageListDao.queryByModeId(orders.getCollageModeId()) == null){
                            CollageList cl = new CollageList();
                            cl.setStatus("0");
                            cl.setCollageModeId(orders.getCollageModeId());
                            collageListDao.save(cl);
                            List<BlindBox> boxList = blindBoxDao.queryBlindBoxByModeId(orders.getCollageModeId());
                            if(boxList.size() > 0){
                                int va = collageModeDao.queryById(orders.getCollageModeId()).getPeopleQuantity();
                                for(BlindBox box : boxList){
                                    int iRandom = 1 + (int)(Math.random()*(va + 1 - 1));
                                    BuyBlindBox bbb = buyBlindBoxDao.queryBuyBlindBoxByIds(cl.getId(), iRandom);
                                    if(bbb == null){
                                        BuyBlindBox buy1 = new BuyBlindBox();
                                        buy1.setClassifyId(box.getClassifyId());
                                        buy1.setCollageListId(cl.getId());
                                        buy1.setUpdateTime(new Date());
                                        buy1.setSerialNumber(iRandom);
                                        buyBlindBoxDao.save(buy1);
                                    }else{
                                        int d;
                                        do {
                                            d = 1 + (int)(Math.random()*(va + 1 - 1));
                                            if (buyBlindBoxDao.queryBuyBlindBoxByIds(cl.getId(), d) == null) {
                                                break;
                                            }
                                        } while (buyBlindBoxDao.queryBuyBlindBoxByIds(cl.getId(), d) != null);
                                        BuyBlindBox buy2 = new BuyBlindBox();
                                        buy2.setClassifyId(box.getClassifyId());
                                        buy2.setCollageListId(cl.getId());
                                        buy2.setUpdateTime(new Date());
                                        buy2.setSerialNumber(d);
                                        buyBlindBoxDao.save(buy2);
                                    }
                                }
                            }
                        }
                        // 整个盲盒的订单改为待发货
                        List<BuyBlindBox> boxList = buyBlindBoxDao.queryBuyBlindBoxByUserId(orders.getCollageListId());
                        for(BuyBlindBox box : boxList){
                            Orders o = ordersDao.queryByIds(orders.getCollageListId(), box.getUserId());
                            if("5".equals(o.getDealStatus())){
                                o.setDealStatus("1");
                                ordersDao.update(o);
                            }
                        }
                    }else{
                        // 还有多个盲盒
                        int iRandom = 1 + (int)(Math.random()*(buySize + 1 - 1));
                        BuyBlindBox buy = buyList.get(iRandom-1);
                        buy.setUserId(orders.getOrderPersonId());
                        buyBlindBoxDao.update(buy);

                        // 随机产品
                        List<Product> productList = productDao.queryProductByClassifyId(buy.getClassifyId());
                        int productSize = productList.size();
                        int productRandom = 1 + (int)(Math.random()*(productSize + 1 - 1));
                        Product product = productList.get(productRandom-1);
                        product.setSales(product.getSales() + 1); // 添加销量
                        productDao.update(product);

                        OrderDetails od = new OrderDetails();
                        od.setOrderNo(orders.getOrderNo());
                        od.setTradeNo(orders.getTradeNo());
                        od.setStoreShopId(product.getStoreShopId());
                        od.setStoreShopName(storeShopDao.queryById(product.getStoreShopId()).getName());
                        od.setClassifyId(product.getClassifyId());
                        od.setClassifyName(classifyDao.queryById(product.getClassifyId()).getName());
                        od.setProductId(product.getId());
                        od.setProductType(product.getType());
                        od.setProductImg(product.getImg());
                        od.setProductName(product.getName());
                        List<SkuRelation> skuList = skuRelationDao.queryByProductId(product.getId());
                        SkuRelation sku = skuList.get(0);
                        od.setProductCode(product.getProductCode());
                        od.setCostPrice(sku.getCostPrice());
                        od.setRelationId(sku.getId());
                        if(sku.getGroupRelation().contains(",")){
                            String[] strings = sku.getGroupRelation().split(",");
                            String str = "";
                            for(int u = 0; u < strings.length; u++){
                                str += specAttributeDao.queryById(Integer.parseInt(strings[u])).getAttributeName() + "，";
                            }
                            od.setSpecAttributeName(str.substring(0, str.length()-1));
                        }else{
                            od.setSpecAttributeName(specAttributeDao.queryById(Integer.parseInt(sku.getGroupRelation())).getAttributeName());
                        }
                        od.setQuantity(1);
                        od.setUnitPrice(sku.getRetailPrice());
                        od.setUpdateTime(new Date());
                        orderDetailsDao.save(od);

                        orders.setPayStatus("1");
                        orders.setDealStatus("5");
                        orders.setIsDel("0");
                        ordersDao.update(orders);
                    }
                }else{
                    // 没有盲盒了

                }

                // 赠送拼团券
                UserCoupon userCoupon = userCouponDao.queryByUserIdAndCouponId(orders.getOrderPersonId(), 1); //拼团券
                if(userCoupon != null){
                    userCoupon.setQuantity(userCoupon.getQuantity() + 1);
                    userCouponDao.update(userCoupon);

                    AccountRecord ar1 = new AccountRecord();
                    ar1.setIntoUserId(orders.getOrderPersonId());
                    ar1.setUpdateTime(new Date());
                    ar1.setType("5");
                    ar1.setAmount(new BigDecimal(1));
                    ar1.setNowAmount(new BigDecimal(userCoupon.getQuantity()));
                    ar1.setSign("1");
                    ar1.setOrderNo(outTradeNo);
                    ar1.setInfo(customerDao.queryById(orders.getOrderPersonId()).getAgentCode() + "购买成功! 您获得拼团券：" + 1);
                    accountRecordDao.save(ar1);
                }else{
                    UserCoupon newUC = new UserCoupon();
                    newUC.setQuantity(1);
                    newUC.setUserId(orders.getOrderPersonId());
                    newUC.setCouponId(1);
                    newUC.setUpdateTime(new Date());
                    userCouponDao.save(newUC);

                    AccountRecord ar2 = new AccountRecord();
                    ar2.setIntoUserId(orders.getOrderPersonId());
                    ar2.setUpdateTime(new Date());
                    ar2.setType("5");
                    ar2.setAmount(new BigDecimal(1));
                    ar2.setNowAmount(new BigDecimal(newUC.getQuantity()));
                    ar2.setSign("1");
                    ar2.setOrderNo(outTradeNo);
                    ar2.setInfo(customerDao.queryById(orders.getOrderPersonId()).getAgentCode() + "购买成功! 您获得拼团券：" + 1);
                    accountRecordDao.save(ar2);
                }

                // 赠送共享券，赠送等额的积分
                Customer customer = customerDao.queryById(orders.getOrderPersonId());
                customer.setQuantityRecord(customer.getQuantityRecord() + 1); // 购买一次就累计一次
                customerDao.update(customer);

                Account acc = accountDao.queryAccountByUserId(customer.getId());
                int give = (int)Math.round(orders.getPayAmount().doubleValue());
                acc.setIntegral(acc.getIntegral() + give);
                accountDao.update(acc);

                AccountRecord ar = new AccountRecord();
                ar.setIntoUserId(customer.getId());
                ar.setUpdateTime(new Date());
                ar.setType("1");
                ar.setAmount(BigDecimal.valueOf(give));
                ar.setNowAmount(BigDecimal.valueOf(acc.getIntegral()));
                ar.setSign("1");
                ar.setOrderNo(outTradeNo);
                ar.setInfo(customerDao.queryById(orders.getOrderPersonId()).getAgentCode() + "购买成功! 您获得积分：" + give);
                accountRecordDao.save(ar);

                if(customer.getParentId() != null && customer.getParentId() != 1198){
                    Customer parentCustomer = customerDao.queryById(customer.getParentId());
                    if(parentCustomer != null){

                        // 统计下级一共购买的数量
                        int sumQuantity = customerDao.queryBySumQuantityRecord(parentCustomer.getId());

                        if(sumQuantity % 9 == 0){

                            UserCoupon puc = userCouponDao.queryByUserIdAndCouponId(parentCustomer.getId(), 2); //共享券
                            if(puc != null){
                                puc.setQuantity(puc.getQuantity() + 1);
                                userCouponDao.update(puc);

                                AccountRecord ar3 = new AccountRecord();
                                ar3.setIntoUserId(parentCustomer.getId());
                                ar3.setUpdateTime(new Date());
                                ar3.setType("6");
                                ar3.setAmount(new BigDecimal(1));
                                ar3.setNowAmount(new BigDecimal(puc.getQuantity()));
                                ar3.setSign("1");
                                ar3.setOrderNo(outTradeNo);
                                ar3.setInfo(customerDao.queryById(orders.getOrderPersonId()).getAgentCode() + "购买成功! 直推累计购买每超过9次,您获得共享券：" + 1);
                                accountRecordDao.save(ar3);
                            }else{
                                UserCoupon newPUC = new UserCoupon();
                                newPUC.setQuantity(1);
                                newPUC.setUserId(parentCustomer.getId());
                                newPUC.setCouponId(2);
                                newPUC.setUpdateTime(new Date());
                                userCouponDao.save(newPUC);

                                AccountRecord ar4 = new AccountRecord();
                                ar4.setIntoUserId(parentCustomer.getId());
                                ar4.setUpdateTime(new Date());
                                ar4.setType("6");
                                ar4.setAmount(new BigDecimal(1));
                                ar4.setNowAmount(new BigDecimal(newPUC.getQuantity()));
                                ar4.setSign("1");
                                ar4.setOrderNo(outTradeNo);
                                ar4.setInfo(customerDao.queryById(orders.getOrderPersonId()).getAgentCode() + "购买成功! 直推累计购买每超过9次,您获得共享券：" + 1);
                                accountRecordDao.save(ar4);
                            }
                        }
                    }
                }

                // 封装 返回值
                StringBuffer buffer = new StringBuffer();
                buffer.append("<xml>");
                buffer.append("<return_code>SUCCESS</return_code>");
                buffer.append("<return_msg>OK</return_msg>");
                buffer.append("</xml>");
                // 给微信服务器返回 成功标示 否则会一直询问服务器是否回调成功
                PrintWriter writer = response.getWriter();
                // 返回
                writer.print(buffer.toString());
            }
        } catch (IOException e) {
            e.printStackTrace();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }


    /**
     * 盲盒支付成功后回调
     * @param request
     * @param response
     */
    @PostMapping("/notify_url_adjust")
    public void blindBoxPayAdjustCallback(HttpServletRequest request, HttpServletResponse response) {
        System.err.println("微信回调接口方法 start ----------------------------");
        String inputLine = "";
        String notityXml = "";
        try {
            while ((inputLine = request.getReader().readLine()) != null) {
                notityXml += inputLine;
            }
            // 关闭流
            request.getReader().close();
            System.err.println("小程序商城支付回调：" + notityXml);
            // 解析成Map
            Map<String, String> map = Units.doXMLParse(notityXml);
            System.err.println(map);
            // 判断 支付是否成功
            if ("SUCCESS".equals(map.get("result_code"))) {
                System.err.println("微信回调返回是否支付成功：是");
                // 获得 返回的商户订单号
                String outTradeNo = map.get("out_trade_no");
                double totalFee = Double.parseDouble(map.get("total_fee")) / 100;
                System.err.println("微信回调返回商户订单号：" + outTradeNo);
                System.err.println("微信回调返回支付金额：" + totalFee);

                Orders orders = ordersDao.queryByOrderNo(outTradeNo);

                List<BuyBlindBox> buyList = buyBlindBoxDao.queryBuyBlindBoxByUserId1(orders.getCollageListId());
                int buySize = buyList.size();
                if(buySize > 0){
                    if(buySize == 1){
                        // 最后一个盲盒
                        BuyBlindBox buy = buyList.get(0);
                        buy.setUserId(orders.getOrderPersonId());
                        buyBlindBoxDao.update(buy);

                        // 盲盒已抽完
                        CollageList collageList = collageListDao.queryById(orders.getCollageListId());
                        collageList.setStatus("1");
                        collageListDao.update(collageList);
                        // 重新生成盲盒
                        if(collageListDao.queryByModeId(orders.getCollageModeId()) == null){
                            CollageList cl = new CollageList();
                            cl.setStatus("0");
                            cl.setCollageModeId(orders.getCollageModeId());
                            collageListDao.save(cl);
                            List<BlindBox> boxList = blindBoxDao.queryBlindBoxByModeId(orders.getCollageModeId());
                            if(boxList.size() > 0){
                                int va = collageModeDao.queryById(orders.getCollageModeId()).getPeopleQuantity();
                                for(BlindBox box : boxList){
                                    int iRandom = 1 + (int)(Math.random()*(va + 1 - 1));
                                    BuyBlindBox bbb = buyBlindBoxDao.queryBuyBlindBoxByIds(cl.getId(), iRandom);
                                    if(bbb == null){
                                        BuyBlindBox buy1 = new BuyBlindBox();
                                        buy1.setClassifyId(box.getClassifyId());
                                        buy1.setCollageListId(cl.getId());
                                        buy1.setUpdateTime(new Date());
                                        buy1.setSerialNumber(iRandom);
                                        buyBlindBoxDao.save(buy1);
                                    }else{
                                        int d;
                                        do {
                                            d = 1 + (int)(Math.random()*(va + 1 - 1));
                                            if (buyBlindBoxDao.queryBuyBlindBoxByIds(cl.getId(), d) == null) {
                                                break;
                                            }
                                        } while (buyBlindBoxDao.queryBuyBlindBoxByIds(cl.getId(), d) != null);
                                        BuyBlindBox buy2 = new BuyBlindBox();
                                        buy2.setClassifyId(box.getClassifyId());
                                        buy2.setCollageListId(cl.getId());
                                        buy2.setUpdateTime(new Date());
                                        buy2.setSerialNumber(d);
                                        buyBlindBoxDao.save(buy2);
                                    }
                                }
                            }
                        }

                        // 随机产品
                        List<Product> productList = productDao.queryProductByClassifyId(buy.getClassifyId());
                        int productSize = productList.size();
                        int productRandom = 1 + (int)(Math.random()*(productSize + 1 - 1));
                        Product product = productList.get(productRandom-1);
                        product.setSales(product.getSales() + 1); // 添加销量
                        productDao.update(product);

                        OrderDetails od = new OrderDetails();
                        od.setOrderNo(orders.getOrderNo());
                        od.setTradeNo(orders.getTradeNo());
                        od.setStoreShopId(product.getStoreShopId());
                        od.setStoreShopName(storeShopDao.queryById(product.getStoreShopId()).getName());
                        od.setClassifyId(product.getClassifyId());
                        od.setClassifyName(classifyDao.queryById(product.getClassifyId()).getName());
                        od.setProductId(product.getId());
                        od.setProductType(product.getType());
                        od.setProductImg(product.getImg());
                        od.setProductName(product.getName());
                        List<SkuRelation> skuList = skuRelationDao.queryByProductId(product.getId());
                        SkuRelation sku = skuList.get(0);
                        od.setProductCode(product.getProductCode());
                        od.setCostPrice(sku.getCostPrice());
                        od.setRelationId(sku.getId());
                        if(sku.getGroupRelation().contains(",")){
                            String[] strings = sku.getGroupRelation().split(",");
                            String str = "";
                            for(int u = 0; u < strings.length; u++){
                                str += specAttributeDao.queryById(Integer.parseInt(strings[u])).getAttributeName() + "，";
                            }
                            od.setSpecAttributeName(str.substring(0, str.length()-1));
                        }else{
                            od.setSpecAttributeName(specAttributeDao.queryById(Integer.parseInt(sku.getGroupRelation())).getAttributeName());
                        }
                        od.setQuantity(1);
                        od.setUnitPrice(sku.getRetailPrice());
                        od.setUpdateTime(new Date());
                        orderDetailsDao.save(od);
                        // 修改订单状态
                        orders.setPayStatus("1");
                        orders.setDealStatus("1");
                        orders.setIsDel("0");
                        ordersDao.update(orders);

                        // 整个盲盒的订单改为待发货
//                        List<BuyBlindBox> boxList = buyBlindBoxDao.queryBuyBlindBoxByUserId(orders.getCollageListId());
//                        for(BuyBlindBox box : boxList){
//                            Orders o = ordersDao.queryByIds(orders.getCollageListId(), box.getUserId());
//                            if("5".equals(o.getDealStatus())){
//                                o.setDealStatus("1");
//                                ordersDao.update(o);
//                            }
//                        }
                    }else{
                        // 还有多个盲盒
                        int iRandom = 1 + (int)(Math.random()*(buySize + 1 - 1));
                        BuyBlindBox buy = buyList.get(iRandom-1);
                        buy.setUserId(orders.getOrderPersonId());
                        buyBlindBoxDao.update(buy);

                        // 随机产品
                        List<Product> productList = productDao.queryProductByClassifyId(buy.getClassifyId());
                        int productSize = productList.size();
                        int productRandom = 1 + (int)(Math.random()*(productSize + 1 - 1));
                        Product product = productList.get(productRandom-1);
                        product.setSales(product.getSales() + 1); // 添加销量
                        productDao.update(product);

                        OrderDetails od = new OrderDetails();
                        od.setOrderNo(orders.getOrderNo());
                        od.setTradeNo(orders.getTradeNo());
                        od.setStoreShopId(product.getStoreShopId());
                        od.setStoreShopName(storeShopDao.queryById(product.getStoreShopId()).getName());
                        od.setClassifyId(product.getClassifyId());
                        od.setClassifyName(classifyDao.queryById(product.getClassifyId()).getName());
                        od.setProductId(product.getId());
                        od.setProductType(product.getType());
                        od.setProductImg(product.getImg());
                        od.setProductName(product.getName());
                        List<SkuRelation> skuList = skuRelationDao.queryByProductId(product.getId());
                        SkuRelation sku = skuList.get(0);
                        od.setProductCode(product.getProductCode());
                        od.setCostPrice(sku.getCostPrice());
                        od.setRelationId(sku.getId());
                        if(sku.getGroupRelation().contains(",")){
                            String[] strings = sku.getGroupRelation().split(",");
                            String str = "";
                            for(int u = 0; u < strings.length; u++){
                                str += specAttributeDao.queryById(Integer.parseInt(strings[u])).getAttributeName() + "，";
                            }
                            od.setSpecAttributeName(str.substring(0, str.length()-1));
                        }else{
                            od.setSpecAttributeName(specAttributeDao.queryById(Integer.parseInt(sku.getGroupRelation())).getAttributeName());
                        }
                        od.setQuantity(1);
                        od.setUnitPrice(sku.getRetailPrice());
                        od.setUpdateTime(new Date());
                        orderDetailsDao.save(od);

                        orders.setPayStatus("1");
                        orders.setDealStatus("1");
                        orders.setIsDel("0");
                        ordersDao.update(orders);
                    }
                }else{
                    // 没有盲盒了

                }

                // 赠送拼团券
                UserCoupon userCoupon = userCouponDao.queryByUserIdAndCouponId(orders.getOrderPersonId(), 1); //拼团券
                if(userCoupon != null){
                    userCoupon.setQuantity(userCoupon.getQuantity() + 1);
                    userCouponDao.update(userCoupon);

                    AccountRecord ar1 = new AccountRecord();
                    ar1.setIntoUserId(orders.getOrderPersonId());
                    ar1.setUpdateTime(new Date());
                    ar1.setType("5");
                    ar1.setAmount(new BigDecimal(1));
                    ar1.setNowAmount(new BigDecimal(userCoupon.getQuantity()));
                    ar1.setSign("1");
                    ar1.setOrderNo(outTradeNo);
                    ar1.setInfo(customerDao.queryById(orders.getOrderPersonId()).getAgentCode() + "购买成功! 您获得拼团券：" + 1);
                    accountRecordDao.save(ar1);
                }else{
                    UserCoupon newUC = new UserCoupon();
                    newUC.setQuantity(1);
                    newUC.setUserId(orders.getOrderPersonId());
                    newUC.setCouponId(1);
                    newUC.setUpdateTime(new Date());
                    userCouponDao.save(newUC);

                    AccountRecord ar2 = new AccountRecord();
                    ar2.setIntoUserId(orders.getOrderPersonId());
                    ar2.setUpdateTime(new Date());
                    ar2.setType("5");
                    ar2.setAmount(new BigDecimal(1));
                    ar2.setNowAmount(new BigDecimal(newUC.getQuantity()));
                    ar2.setSign("1");
                    ar2.setOrderNo(outTradeNo);
                    ar2.setInfo(customerDao.queryById(orders.getOrderPersonId()).getAgentCode() + "购买成功! 您获得拼团券：" + 1);
                    accountRecordDao.save(ar2);
                }

                // 赠送共享券，赠送等额的积分
                Customer customer = customerDao.queryById(orders.getOrderPersonId());
                customer.setQuantityRecord(customer.getQuantityRecord() + 1); // 购买一次就累计一次
                customerDao.update(customer);

                Account acc = accountDao.queryAccountByUserId(customer.getId());
                int give = (int)Math.round(orders.getPayAmount().doubleValue());
                acc.setIntegral(acc.getIntegral() + give);
                accountDao.update(acc);

                AccountRecord ar = new AccountRecord();
                ar.setIntoUserId(customer.getId());
                ar.setUpdateTime(new Date());
                ar.setType("1");
                ar.setAmount(BigDecimal.valueOf(give));
                ar.setNowAmount(BigDecimal.valueOf(acc.getIntegral()));
                ar.setSign("1");
                ar.setOrderNo(outTradeNo);
                ar.setInfo(customerDao.queryById(orders.getOrderPersonId()).getAgentCode() + "购买成功! 您获得积分：" + give);
                accountRecordDao.save(ar);

                if(customer.getParentId() != null && customer.getParentId() != 1198){
                    Customer parentCustomer = customerDao.queryById(customer.getParentId());
                    if(parentCustomer != null){

                        // 统计下级一共购买的数量
                        int sumQuantity = customerDao.queryBySumQuantityRecord(parentCustomer.getId());

                        if(sumQuantity % 9 == 0){

                            UserCoupon puc = userCouponDao.queryByUserIdAndCouponId(parentCustomer.getId(), 2); //共享券
                            if(puc != null){
                                puc.setQuantity(puc.getQuantity() + 1);
                                userCouponDao.update(puc);

                                AccountRecord ar3 = new AccountRecord();
                                ar3.setIntoUserId(parentCustomer.getId());
                                ar3.setUpdateTime(new Date());
                                ar3.setType("6");
                                ar3.setAmount(new BigDecimal(1));
                                ar3.setNowAmount(new BigDecimal(puc.getQuantity()));
                                ar3.setSign("1");
                                ar3.setOrderNo(outTradeNo);
                                ar3.setInfo(customerDao.queryById(orders.getOrderPersonId()).getAgentCode() + "购买成功! 直推累计购买每超过9次,您获得共享券：" + 1);
                                accountRecordDao.save(ar3);
                            }else{
                                UserCoupon newPUC = new UserCoupon();
                                newPUC.setQuantity(1);
                                newPUC.setUserId(parentCustomer.getId());
                                newPUC.setCouponId(2);
                                newPUC.setUpdateTime(new Date());
                                userCouponDao.save(newPUC);

                                AccountRecord ar4 = new AccountRecord();
                                ar4.setIntoUserId(parentCustomer.getId());
                                ar4.setUpdateTime(new Date());
                                ar4.setType("6");
                                ar4.setAmount(new BigDecimal(1));
                                ar4.setNowAmount(new BigDecimal(newPUC.getQuantity()));
                                ar4.setSign("1");
                                ar4.setOrderNo(outTradeNo);
                                ar4.setInfo(customerDao.queryById(orders.getOrderPersonId()).getAgentCode() + "购买成功! 直推累计购买每超过9次,您获得共享券：" + 1);
                                accountRecordDao.save(ar4);
                            }
                        }
                    }
                }

                // 封装 返回值
                StringBuffer buffer = new StringBuffer();
                buffer.append("<xml>");
                buffer.append("<return_code>SUCCESS</return_code>");
                buffer.append("<return_msg>OK</return_msg>");
                buffer.append("</xml>");
                // 给微信服务器返回 成功标示 否则会一直询问服务器是否回调成功
                PrintWriter writer = response.getWriter();
                // 返回
                writer.print(buffer.toString());
            }
        } catch (IOException e) {
            e.printStackTrace();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }


    /**
     * 获取微信AccessToken
     * @return
     */
    public static String getAccessToken() {
        Map<String, Object> params = new HashMap<>();
        params.put("grant_type", "client_credential");
        params.put("appid", Constants.wxAppId);
        params.put("secret", Constants.wxAppSecret);
        String result = HttpRequestUtil.sendPostMap(Constants.AccessTokenURL, params);
        System.err.println("获取access_tokenjson信息:" + result);
        JSONObject json = JSONObject.fromObject(result);
        // 获取密令（access_token）
        String access_token = json.get("access_token").toString();
        System.err.println("获得的access_token值-----" + access_token);
        return access_token;
    }


    /**
     * 获取小程序二维码
     *
     * @throws Exception
     */
    @GetMapping("/erweima.json")
    public ResponseServer GetquaCode(String parentid, @RequestParam(required = false) String pageUrl,
                                     @RequestParam(required = false) String params,
                                     @RequestParam(required = false) boolean flag,
                                     @RequestParam(required = false) String bgimg) {
        InputStream inputStream = null;
        OutputStream outputStream = null;
        String path;
        String p;
        try {
            String access_token = getAccessToken();
            System.err.println("二维码参数" + parentid);
            String scene = parentid + "&" + pageUrl + "&" + params;
            System.err.println("二维码传递的参数" + scene);
            RestTemplate rest = new RestTemplate();
            String url = "https://api.weixin.qq.com/wxa/getwxacodeunlimit?access_token=" + access_token;
            Map<String, Object> param = new HashMap<>();
            param.put("scene", scene);
            param.put("page", "pages/index/index");
            param.put("width", 280);
            param.put("auto_color", false);
            Map<String, Object> line_color = new HashMap<>();
            line_color.put("r", 0);
            line_color.put("g", 0);
            line_color.put("b", 0);
            param.put("line_color", line_color);
            param.put("is_hyaline", false);
            MultiValueMap<String, String> headers = new LinkedMultiValueMap<>();
            HttpEntity requestEntity = new HttpEntity(param, headers);
            ResponseEntity<byte[]> entity = rest.exchange(url, HttpMethod.POST, requestEntity, byte[].class, new Object[0]);
            System.err.println("调用小程序生成微信永久小程序码URL接口返回结果:" + entity.getBody());
            byte[] result = entity.getBody();
            inputStream = new ByteArrayInputStream(result);
            File springBootpath = new File(ResourceUtils.getURL("classpath:").getPath());
            File upload = new File(springBootpath.getAbsolutePath());
            path = upload.getAbsolutePath();
            path = path.substring(0, path.lastIndexOf("zhouheroic_plan/"));
            p = URLDecoder.decode(path, "utf-8"); //处理空格转化为%20
            // 文件上传的绝对路径
            File file;
            if (pageUrl != null && pageUrl != "") {
                path = p + "img" + File.separator + "share";
                file = new File(path + "/" + parentid + pageUrl + ".png");
            } else {
                path = p + "img" + File.separator + "erweima";
                file = new File(path + "/" + parentid + ".png");
            }
            System.err.println("存文件路径" + path);
            if (!file.exists()) {
                file.createNewFile();
            }
            outputStream = new FileOutputStream(file);
            int len = 0;
            byte[] buf = new byte[1024];
            while ((len = inputStream.read(buf, 0, 1024)) != -1) {
                outputStream.write(buf, 0, len);
            }
            outputStream.flush();
        } catch (Exception e) {
            e.printStackTrace();
            return ResponseServer.error("");
        } finally {
            if (inputStream != null) {
                try {
                    inputStream.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if (outputStream != null) {
                try {
                    outputStream.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        if (flag && pageUrl != null && pageUrl != "") {
            FileUtil fileUtil = new FileUtil();
            String imageurl = path + "/" + parentid + pageUrl + ".png";
            String imageinPath = bgimg;
            fileUtil.changeImage(imageurl, imageinPath);
            return ResponseServer.success();
        } else {
            return ResponseServer.success();
        }
    }


    /**
     * 查询订单物流轨迹
     * @param expCode
     * @param expNo
     * @return
     */
    @PostMapping("/getWuLiuInfo")
    public String getOrderTracesByJson(String expCode, String expNo) {
        try {
            String json = CreateUnifiedOrder.getWuliu(expNo);
            return json;
        } catch (Exception e) {
            e.printStackTrace();
            return "";
        }
    }


    /**
     * 获取礼包产品
     * @return
     */
    @GetMapping("/getProductByType3")
    public ResponseServer getProductByType3(){
        List<Product> voList = productDao.queryProductByType3();
        return ResponseServer.success(voList);
    }


    /**
     * 购买礼包，微信支付
     * @param request
     * @param productId
     * @param openId
     * @param consigneeName
     * @param fullAddress
     * @param consigneePhone
     * @param userId
     * @param freight
     * @return
     */
    @PostMapping("/share/pay")
    public ResponseServer sharePay(HttpServletRequest request, @RequestParam(required = false) Integer productId,
                                  @RequestParam(required = false) String openId,
                                  @RequestParam(required = false) String consigneeName,
                                  @RequestParam(required = false) String fullAddress,
                                  @RequestParam(required = false) String consigneePhone,
                                  @RequestParam(required = false) Integer userId,
                                  @RequestParam(required = false) BigDecimal freight,
                                   @RequestParam(required = false) BigDecimal couponPrice) throws Exception {

        System.err.println("-------------创建订单传递的参数：productId= " + productId);
        System.err.println("-------------创建订单传递的参数：openId= " + openId);
        System.err.println("-------------创建订单传递的参数：consigneeName= " + consigneeName);
        System.err.println("-------------创建订单传递的参数：fullAddress= " + fullAddress);
        System.err.println("-------------创建订单传递的参数：consigneePhone= " + consigneePhone);
        System.err.println("-------------创建订单传递的参数：userId= " + userId);
        System.err.println("-------------创建订单传递的参数：freight= " + freight);

        Map<String, String> maps = new HashMap<>();

        Product product = productDao.queryById(productId);
        if(product == null){
            maps.put("prepayId", "");
            maps.put("msg", "支付失败,产品信息错误");
            return ResponseServer.success(maps);
        }
        BigDecimal totalPrice; // 需要支付的金额
        // 商户订单号
        String outTradeNo = "BEE" + Units.getOrderIdByTime().replaceAll("-", "");
        // 交易号
        String tradeNo = "JYH" + Units.getOrderIdByTime().replaceAll("-", "");
        if (freight == null) {
            freight = BigDecimal.valueOf(0.0);
        }
        if(couponPrice == null){
            couponPrice = BigDecimal.valueOf(0.0);
        }
        List<SkuRelation> skuList = skuRelationDao.queryByProductId(productId);
        SkuRelation sku = skuList.get(0);
        BigDecimal totalAmount = sku.getRetailPrice(); // 总金额
        totalPrice = sku.getRetailPrice().add(freight).subtract(couponPrice);
        Map<String, String> map;
        if (totalPrice.doubleValue() > 0) {
            Map<String, Object> wxPay = new HashMap<>();
            wxPay.put("totalPrice", totalPrice.doubleValue());
            wxPay.put("outTradeNo", outTradeNo);
            wxPay.put("openId", openId);
            wxPay.put("notifyUrl", Constants.notify_url_pack);
            wxPay.put("wxPayAppId", Constants.wxAppId);
            wxPay.put("tradeType", Constants.trade_type);
            String paramBuffer = CreateUnifiedOrder.UnifiedOrder(request, wxPay);
            map = Units.doXMLParse(HttpRequestUtil.sendPost(Constants.pay_url, new String(paramBuffer.getBytes(), "UTF-8")));
            // 创建订单
            if (map != null) {
                Orders orders = new Orders();
                orders.setOrderNo(outTradeNo);
                orders.setTradeNo(tradeNo);
                orders.setTotalAmount(totalAmount); // 总金额
                orders.setPayAmount(totalPrice);  // 实际支付金额
                orders.setCouponAmount(couponPrice);  // 优惠券抵扣金额
                orders.setFreight(freight); // 运费金额
                orders.setPayStatus("0");
                orders.setPayType("0");
                orders.setDealStatus("0");
                orders.setRefundStatus("0");
                orders.setPrepayId(map.get("prepay_id"));
                orders.setOrderPersonId(userId);
                orders.setConsigneeName(consigneeName);
                orders.setConsigneePhone(consigneePhone);
                orders.setAddress(fullAddress);
                orders.setUpdateTime(new Date());
                orders.setIsDel("0");
                orders.setIsRun("0");
                orders.setLastCollage("0");
                orders.setRemarks("无");
                orders.setProductId(product.getId());
                ordersDao.save(orders);

                OrderDetails od = new OrderDetails();
                od.setOrderNo(orders.getOrderNo());
                od.setTradeNo(orders.getTradeNo());
                od.setStoreShopId(product.getStoreShopId());
                od.setStoreShopName(storeShopDao.queryById(product.getStoreShopId()).getName());
                od.setClassifyId(product.getClassifyId());
                od.setClassifyName(classifyDao.queryById(product.getClassifyId()).getName());
                od.setProductId(product.getId());
                od.setProductType(product.getType()); // 礼包
                od.setProductImg(product.getImg());
                od.setProductName(product.getName());

                od.setProductCode(product.getProductCode());
                od.setCostPrice(sku.getCostPrice());
//                List<SkuRelation> skuList = skuRelationDao.queryByProductId(product.getId());
//                SkuRelation sku = skuList.get(0);
                od.setRelationId(sku.getId());
                if(sku.getGroupRelation().contains(",")){
                    String[] strings = sku.getGroupRelation().split(",");
                    String str = "";
                    for(int u = 0; u < strings.length; u++){
                        str += specAttributeDao.queryById(Integer.parseInt(strings[u])).getAttributeName() + "，";
                    }
                    od.setSpecAttributeName(str.substring(0, str.length()-1));
                }else{
                    od.setSpecAttributeName(specAttributeDao.queryById(Integer.parseInt(sku.getGroupRelation())).getAttributeName());
                }
                od.setQuantity(1);
                od.setUnitPrice(sku.getRetailPrice());
                od.setUpdateTime(new Date());
                orderDetailsDao.save(od);

                maps.put("prepayId", map.get("prepay_id"));
                maps.put("outTradeNo", outTradeNo);
                return ResponseServer.success(maps);
            }
        }
        maps.put("prepayId", "");
        maps.put("msg", "支付失败,请重试");
        return ResponseServer.success(maps);
    }


    /**
     * 礼包支付成功后回调
     * @param request
     * @param response
     */
    @PostMapping("/notify_url_pack")
    public void sharePayCallback(HttpServletRequest request, HttpServletResponse response) {
        System.err.println("微信回调接口方法 start ----------------------------");
        String inputLine = "";
        String notityXml = "";
        try {
            while ((inputLine = request.getReader().readLine()) != null) {
                notityXml += inputLine;
            }
            // 关闭流
            request.getReader().close();
            System.err.println("小程序商城支付回调：" + notityXml);
            // 解析成Map
            Map<String, String> map = Units.doXMLParse(notityXml);
            System.err.println(map);
            // 判断 支付是否成功
            if ("SUCCESS".equals(map.get("result_code"))) {
                System.err.println("微信回调返回是否支付成功：是");
                // 获得 返回的商户订单号
                String outTradeNo = map.get("out_trade_no");
                double totalFee = Double.parseDouble(map.get("total_fee")) / 100;
                System.err.println("微信回调返回商户订单号：" + outTradeNo);
                System.err.println("微信回调返回支付金额：" + totalFee);

                Orders orders = ordersDao.queryByOrderNo(outTradeNo);

                // 修改订单状态
                orders.setPayStatus("1");
                orders.setDealStatus("1");
                orders.setIsDel("0");
                ordersDao.update(orders);

                Product product = productDao.queryById(orders.getProductId());
                product.setSales(product.getSales() + 1); // 添加销量
                productDao.update(product);

                Customer customer = customerDao.queryById(orders.getOrderPersonId());

                Account acc = accountDao.queryAccountByUserId(customer.getId());
                int give = (int)Math.round(orders.getPayAmount().doubleValue());
                acc.setIntegral(acc.getIntegral() + give);
                accountDao.update(acc);

                AccountRecord ar = new AccountRecord();
                ar.setIntoUserId(customer.getId());
                ar.setUpdateTime(new Date());
                ar.setType("1");
                ar.setAmount(BigDecimal.valueOf(give));
                ar.setNowAmount(BigDecimal.valueOf(acc.getIntegral()));
                ar.setSign("1");
                ar.setOrderNo(outTradeNo);
                ar.setInfo(customerDao.queryById(orders.getOrderPersonId()).getAgentCode() + "购买成功! 您获得积分：" + give);
                accountRecordDao.save(ar);

                // 处理等级 纳新红包 服务补助 培训津贴
                // 调用共享模式
                sharingMode(orders);
                addAchievement(orders);

                // 封装 返回值
                StringBuffer buffer = new StringBuffer();
                buffer.append("<xml>");
                buffer.append("<return_code>SUCCESS</return_code>");
                buffer.append("<return_msg>OK</return_msg>");
                buffer.append("</xml>");
                // 给微信服务器返回 成功标示 否则会一直询问服务器是否回调成功
                PrintWriter writer = response.getWriter();
                // 返回
                writer.print(buffer.toString());
            }
        } catch (IOException e) {
            e.printStackTrace();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }


    /**
     * 购买中秋活动产品，微信支付
     * @param request
     * @param productId
     * @param openId
     * @param consigneeName
     * @param fullAddress
     * @param consigneePhone
     * @param userId
     * @param freight
     * @return
     */
    @PostMapping("/autumn/pay")
    public ResponseServer autumnPay(HttpServletRequest request, @RequestParam(required = false) Integer productId,
                                   @RequestParam(required = false) String openId,
                                   @RequestParam(required = false) String consigneeName,
                                   @RequestParam(required = false) String fullAddress,
                                   @RequestParam(required = false) String consigneePhone,
                                   @RequestParam(required = false) Integer userId,
                                   @RequestParam(required = false) BigDecimal freight) throws Exception {

        System.err.println("-------------创建订单传递的参数：productId= " + productId);
        System.err.println("-------------创建订单传递的参数：openId= " + openId);
        System.err.println("-------------创建订单传递的参数：consigneeName= " + consigneeName);
        System.err.println("-------------创建订单传递的参数：fullAddress= " + fullAddress);
        System.err.println("-------------创建订单传递的参数：consigneePhone= " + consigneePhone);
        System.err.println("-------------创建订单传递的参数：userId= " + userId);
        System.err.println("-------------创建订单传递的参数：freight= " + freight);

        Map<String, String> maps = new HashMap<>();

        Product product = productDao.queryById(productId);
        if(product == null){
            maps.put("prepayId", "");
            maps.put("msg", "支付失败,产品信息错误");
            return ResponseServer.success(maps);
        }
        BigDecimal totalPrice; // 需要支付的金额
        // 商户订单号
        String outTradeNo = "BEE" + Units.getOrderIdByTime().replaceAll("-", "");
        // 交易号
        String tradeNo = "JYH" + Units.getOrderIdByTime().replaceAll("-", "");
        if (freight == null) {
            freight = BigDecimal.valueOf(0.0);
        }
        List<SkuRelation> skuList = skuRelationDao.queryByProductId(productId);
        SkuRelation sku = skuList.get(0);
        BigDecimal totalAmount = sku.getRetailPrice(); // 总金额
        totalPrice = sku.getRetailPrice().add(freight);
        Map<String, String> map;
        if (totalPrice.doubleValue() > 0) {
            Map<String, Object> wxPay = new HashMap<>();
            wxPay.put("totalPrice", totalPrice.doubleValue());
            wxPay.put("outTradeNo", outTradeNo);
            wxPay.put("openId", openId);
            wxPay.put("notifyUrl", Constants.notify_url_autumn);
            wxPay.put("wxPayAppId", Constants.wxAppId);
            wxPay.put("tradeType", Constants.trade_type);
            String paramBuffer = CreateUnifiedOrder.UnifiedOrder(request, wxPay);
            map = Units.doXMLParse(HttpRequestUtil.sendPost(Constants.pay_url, new String(paramBuffer.getBytes(), "UTF-8")));
            // 创建订单
            if (map != null) {
                Orders orders = new Orders();
                orders.setOrderNo(outTradeNo);
                orders.setTradeNo(tradeNo);
                orders.setTotalAmount(totalAmount); // 总金额
                orders.setPayAmount(totalPrice);  // 实际支付金额
                orders.setCouponAmount(new BigDecimal(0));  // 优惠券抵扣金额
                orders.setFreight(freight); // 运费金额
                orders.setPayStatus("0");
                orders.setPayType("0");
                orders.setDealStatus("0");
                orders.setRefundStatus("0");
                orders.setPrepayId(map.get("prepay_id"));
                orders.setOrderPersonId(userId);
                orders.setConsigneeName(consigneeName);
                orders.setConsigneePhone(consigneePhone);
                orders.setAddress(fullAddress);
                orders.setUpdateTime(new Date());
                orders.setIsDel("0");
                orders.setIsRun("0");
                orders.setRemarks("中秋订单");
                orders.setProductId(product.getId());
                ordersDao.save(orders);

                OrderDetails od = new OrderDetails();
                od.setOrderNo(orders.getOrderNo());
                od.setTradeNo(orders.getTradeNo());
                od.setStoreShopId(product.getStoreShopId());
                od.setStoreShopName(storeShopDao.queryById(product.getStoreShopId()).getName());
                od.setClassifyId(product.getClassifyId());
                od.setClassifyName(classifyDao.queryById(product.getClassifyId()).getName());
                od.setProductId(product.getId());
                od.setProductType(product.getType());
                od.setProductImg(product.getImg());
                od.setProductName(product.getName());

                od.setProductCode(product.getProductCode());
                od.setCostPrice(sku.getCostPrice());
                od.setRelationId(sku.getId());
                if(sku.getGroupRelation().contains(",")){
                    String[] strings = sku.getGroupRelation().split(",");
                    String str = "";
                    for(int u = 0; u < strings.length; u++){
                        str += specAttributeDao.queryById(Integer.parseInt(strings[u])).getAttributeName() + "，";
                    }
                    od.setSpecAttributeName(str.substring(0, str.length()-1));
                }else{
                    od.setSpecAttributeName(specAttributeDao.queryById(Integer.parseInt(sku.getGroupRelation())).getAttributeName());
                }
                od.setQuantity(1);
                od.setUnitPrice(sku.getRetailPrice());
                od.setUpdateTime(new Date());
                orderDetailsDao.save(od);

                maps.put("prepayId", map.get("prepay_id"));
                maps.put("outTradeNo", outTradeNo);
                return ResponseServer.success(maps);
            }
        }
        maps.put("prepayId", "");
        maps.put("msg", "支付失败,请重试");
        return ResponseServer.success(maps);
    }


    /**
     * 中秋活动产品支付成功后回调
     * @param request
     * @param response
     */
    @PostMapping("/notify_url_autumn")
    public void autumnPayCallback(HttpServletRequest request, HttpServletResponse response) {
        System.err.println("微信回调接口方法 start ----------------------------");
        String inputLine = "";
        String notityXml = "";
        try {
            while ((inputLine = request.getReader().readLine()) != null) {
                notityXml += inputLine;
            }
            // 关闭流
            request.getReader().close();
            System.err.println("小程序商城支付回调：" + notityXml);
            // 解析成Map
            Map<String, String> map = Units.doXMLParse(notityXml);
            System.err.println(map);
            // 判断 支付是否成功
            if ("SUCCESS".equals(map.get("result_code"))) {
                System.err.println("微信回调返回是否支付成功：是");
                // 获得 返回的商户订单号
                String outTradeNo = map.get("out_trade_no");
                double totalFee = Double.parseDouble(map.get("total_fee")) / 100;
                System.err.println("微信回调返回商户订单号：" + outTradeNo);
                System.err.println("微信回调返回支付金额：" + totalFee);

                Orders orders = ordersDao.queryByOrderNo(outTradeNo);

                // 修改订单状态
                orders.setPayStatus("1");
                orders.setDealStatus("1");
                orders.setIsDel("0");
                ordersDao.update(orders);

                Product product = productDao.queryById(orders.getProductId());
                product.setSales(product.getSales() + 1); // 添加销量
                productDao.update(product);

                Customer customer = customerDao.queryById(orders.getOrderPersonId());

                Account acc = accountDao.queryAccountByUserId(customer.getId());
                int give = (int)Math.round(orders.getPayAmount().doubleValue());
                acc.setIntegral(acc.getIntegral() + give);
                accountDao.update(acc);

                AccountRecord ar = new AccountRecord();
                ar.setIntoUserId(customer.getId());
                ar.setUpdateTime(new Date());
                ar.setType("1");
                ar.setAmount(BigDecimal.valueOf(give));
                ar.setNowAmount(BigDecimal.valueOf(acc.getIntegral()));
                ar.setSign("1");
                ar.setOrderNo(outTradeNo);
                ar.setInfo(customerDao.queryById(orders.getOrderPersonId()).getAgentCode() + "购买成功! 您获得积分：" + give);
                accountRecordDao.save(ar);

                // 封装 返回值
                StringBuffer buffer = new StringBuffer();
                buffer.append("<xml>");
                buffer.append("<return_code>SUCCESS</return_code>");
                buffer.append("<return_msg>OK</return_msg>");
                buffer.append("</xml>");
                // 给微信服务器返回 成功标示 否则会一直询问服务器是否回调成功
                PrintWriter writer = response.getWriter();
                // 返回
                writer.print(buffer.toString());
            }
        } catch (IOException e) {
            e.printStackTrace();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }


    /**
     * 共享模式
     * 处理客户购买购买礼包后的数据
     * @param orders
     */
    public void sharingMode(Orders orders){
        try {

            // 下单人
            Customer customer = customerDao.queryById(orders.getOrderPersonId());

            // 自己累积购买金额
            BigDecimal ownTotalBuy = customer.getOwnTotalBuy();

            // 上级信息
            Customer parentCustomer = null;
            Account parentAccount = null;
            if(customer.getParentId() != null && customer.getParentId() != 1198){
                parentCustomer = customerDao.queryById(customer.getParentId());
                parentAccount = accountDao.queryAccountByUserId(parentCustomer.getId());
            }

            // 系统当前时间
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
            Date todate = new Date();
            Calendar now = Calendar.getInstance();
            now.setTime(todate);
            String date = sdf.format(now.getTime());
            now.add(Calendar.DAY_OF_MONTH, -1);
            String date1 = sdf.format(now.getTime());
            // 获取今日奖金池
            PrizePool prizePool = prizePoolDao.queryByToday(date);
            if(prizePool == null){
                prizePool = prizePoolDao.queryByToday(date1); // TODO 每天凌晨0点-2点的共享订单，统计到昨天计算，2点后的统计到今日计算
            }
            prizePool.setTotalMoney(prizePool.getTotalMoney().add(orders.getTotalAmount())); // 加奖池 -产品金额
            prizePool.setPayMoney(prizePool.getPayMoney().add(orders.getPayAmount())); // 支付金额

            // 一共的金额
            BigDecimal sumAmount = orders.getTotalAmount().add(ownTotalBuy);

            // 下单总金额
            Double totalAmount = sumAmount.doubleValue();

            // 分红包券
            //if(parentCustomer.getLevelCopyId() > 1){ // 上级大于游客 // TODO 修改为游客也分红包券
                if(orders.getTotalAmount().doubleValue() >= 369 && orders.getTotalAmount().doubleValue() < 3690){
                    prizePool.setRedPackQuantity(prizePool.getRedPackQuantity() + 1); // 加奖金池红包券
                    parentAccount.setRedPacket(parentAccount.getRedPacket() + 1);// 加上级个人红包券

                }else if(orders.getTotalAmount().doubleValue() >= 3690 && orders.getTotalAmount().doubleValue() < 36900){
                    prizePool.setRedPackQuantity(prizePool.getRedPackQuantity() + 10); // 加奖金池红包券
                    parentAccount.setRedPacket(parentAccount.getRedPacket() + 10);// 加上级个人红包券

                }else if(orders.getTotalAmount().doubleValue() >= 36900){
                    prizePool.setRedPackQuantity(prizePool.getRedPackQuantity() + 100); // 加奖金池红包券
                    parentAccount.setRedPacket(parentAccount.getRedPacket() + 100);// 加上级个人红包券
                }
                accountDao.update(parentAccount);
                prizePoolDao.update(prizePool);
            //}

            customer.setOwnTotalBuy(sumAmount);
            customerDao.update(customer);

            // 升级

            // 369礼包
            if(totalAmount >= 369 && totalAmount < 3690){

                // 判断自己是否需要升级 菜鸟
                if(customer.getLevelCopyId() < 2){
                    customer.setLevelCopyId(2);
                    if("0".equals(customer.getIsActiveCopy())){
                        customer.setIsActiveCopy("1"); // 激活共享等级
                    }
                    // 同步拼团等级
                    customer.setLevelId(2);
                    if("0".equals(customer.getIsActive())){
                        // 是否购买过拼团产品
                        List<Orders> ordersList = ordersDao.queryOrdersByUserIdIsBuyCollage(customer.getId());
                        if(ordersList.size() > 0){
                            customer.setIsActive("1"); // 激活拼团等级
                        }
                    }
                    // TODO 直播等级 等待完善
                    // 同步直播等级
                    customer.setLevelCopy1Id(2);
                    // 判断是否购买过直播产品，买过就激活
                    customer.setIsActiveCopy1("0"); // 待激活直播等级

                    // 同步蜜淘等级
                    customer.setLevelCopy2Id(2);
                    if("0".equals(customer.getIsActiveCopy2())){
                        // 是否购买过蜜淘产品
                        List<GoodsOrders> ordersList = goodsOrdersDao.queryGoodsOrdersByUserIdIsBuyBeeAmoy(customer.getId());
                        if(ordersList.size() > 0){
                            customer.setIsActive("1"); // 激活蜜淘等级
                        }
                    }

                    customerDao.update(customer);

                    if(parentCustomer.getLevelCopyId() <= customer.getLevelCopyId()){
                        // 判断上级是否满足升级 高手
                        List<Customer> list2 = customerDao.queryCustomerByLevelCopyId(2, parentCustomer.getId()); // 2=菜鸟
                        int size2 = list2.size();
                        if(size2 >= 9){
                            if(parentCustomer.getLevelCopyId() > 1){
                                parentCustomer.setLevelCopyId(3); // 升级为高手
                                // 同步拼团等级
                                parentCustomer.setLevelId(3);
                                if("0".equals(parentCustomer.getIsActive())){
                                    // 是否购买过拼团产品
                                    List<Orders> ordersList = ordersDao.queryOrdersByUserIdIsBuyCollage(parentCustomer.getId());
                                    if(ordersList.size() > 0){
                                        parentCustomer.setIsActive("1"); // 激活拼团等级
                                    }
                                }
                                // TODO 直播等级 等待完善
                                // 同步直播等级
                                parentCustomer.setLevelCopy1Id(3);
                                // 判断是否购买过直播产品，买过就激活
                                parentCustomer.setIsActiveCopy1("0"); // 待激活直播等级

                                // 同步蜜淘等级
                                parentCustomer.setLevelCopy2Id(3);
                                if("0".equals(parentCustomer.getIsActiveCopy2())){
                                    // 是否购买过蜜淘产品
                                    List<GoodsOrders> ordersList = goodsOrdersDao.queryGoodsOrdersByUserIdIsBuyBeeAmoy(parentCustomer.getId());
                                    if(ordersList.size() > 0){
                                        parentCustomer.setIsActive("1"); // 激活蜜淘等级
                                        if(parentCustomer.getAddUpUpgrade().doubleValue() < 10000){
                                            parentCustomer.setAddUpUpgradeFiction(BigDecimal.valueOf(10000).subtract(parentCustomer.getAddUpUpgrade()).add(parentCustomer.getAddUpUpgradeFiction()));
                                        }
                                    }
                                }

                                customerDao.update(parentCustomer);

                                if(parentCustomer.getParentId() != null && parentCustomer.getParentId() != 1198 && parentCustomer.getLevelCopyId() != 11){
                                    // 判断再上一级是否满足升级 王者
                                    Customer top3Customer = customerDao.queryById(parentCustomer.getParentId());
                                    if(top3Customer.getLevelCopyId() <= parentCustomer.getLevelCopyId()){
                                        List<Customer> list3 = customerDao.queryCustomerByLevelCopyId_killer(3, top3Customer.getId()); // 3=高手
                                        int size3 = list3.size();
                                        if(size3 >= 6){
                                            if(top3Customer.getLevelCopyId() > 1){
                                                top3Customer.setLevelCopyId(4); // 升级为王者

                                                // 同步拼团等级
                                                top3Customer.setLevelId(4);
                                                if("0".equals(top3Customer.getIsActive())){
                                                    // 是否购买过拼团产品
                                                    List<Orders> ordersList = ordersDao.queryOrdersByUserIdIsBuyCollage(top3Customer.getId());
                                                    if(ordersList.size() > 0){
                                                        top3Customer.setIsActive("1"); // 激活拼团等级
                                                    }
                                                }
                                                // TODO 直播等级 等待完善
                                                // 同步直播等级
                                                top3Customer.setLevelCopy1Id(4);
                                                // 判断是否购买过直播产品，买过就激活
                                                top3Customer.setIsActiveCopy1("0"); // 待激活直播等级

                                                // 同步蜜淘等级
                                                top3Customer.setLevelCopy2Id(4);
                                                if("0".equals(top3Customer.getIsActiveCopy2())){
                                                    // 是否购买过蜜淘产品
                                                    List<GoodsOrders> ordersList = goodsOrdersDao.queryGoodsOrdersByUserIdIsBuyBeeAmoy(top3Customer.getId());
                                                    if(ordersList.size() > 0){
                                                        top3Customer.setIsActive("1"); // 激活蜜淘等级
                                                        if(top3Customer.getAddUpUpgrade().doubleValue() < 50000){
                                                            top3Customer.setAddUpUpgradeFiction(BigDecimal.valueOf(50000).subtract(top3Customer.getAddUpUpgrade()).add(top3Customer.getAddUpUpgradeFiction()));
                                                        }
                                                    }
                                                }

                                                customerDao.update(top3Customer);
                                            }

                                            if(top3Customer.getParentId() != null && top3Customer.getParentId() != 1198 && top3Customer.getLevelCopyId() != 11){
                                                // 判断再上一级是否满足升级 至尊
                                                Customer top4Customer = customerDao.queryById(top3Customer.getParentId());
                                                if(top4Customer.getLevelCopyId() <= top3Customer.getLevelCopyId()){
                                                    List<Customer> list4 = customerDao.queryCustomerByLevelCopyId_theKing(4, top4Customer.getId()); // 4=王者
                                                    int size4 = list4.size();
                                                    if(size4 >= 3){
                                                        if(top4Customer.getLevelCopyId() > 1) {
                                                            top4Customer.setLevelCopyId(5); // 升级到至尊

                                                            // 同步拼团等级
                                                            top4Customer.setLevelId(5);
                                                            if("0".equals(top4Customer.getIsActive())){
                                                                // 是否购买过拼团产品
                                                                List<Orders> ordersList = ordersDao.queryOrdersByUserIdIsBuyCollage(top4Customer.getId());
                                                                if(ordersList.size() > 0){
                                                                    top4Customer.setIsActive("1"); // 激活拼团等级
                                                                }
                                                            }
                                                            // TODO 直播等级 等待完善
                                                            // 同步直播等级
                                                            top4Customer.setLevelCopy1Id(5);
                                                            // 判断是否购买过直播产品，买过就激活
                                                            top4Customer.setIsActiveCopy1("0"); // 待激活直播等级

                                                            // 同步蜜淘等级
                                                            top4Customer.setLevelCopy2Id(5);
                                                            if("0".equals(top4Customer.getIsActiveCopy2())){
                                                                // 是否购买过蜜淘产品
                                                                List<GoodsOrders> ordersList = goodsOrdersDao.queryGoodsOrdersByUserIdIsBuyBeeAmoy(top4Customer.getId());
                                                                if(ordersList.size() > 0){
                                                                    top4Customer.setIsActive("1"); // 激活蜜淘等级
                                                                    if(top4Customer.getAddUpUpgrade().doubleValue() < 100000){
                                                                        top4Customer.setAddUpUpgradeFiction(BigDecimal.valueOf(100000).subtract(top4Customer.getAddUpUpgrade()).add(top4Customer.getAddUpUpgradeFiction()));
                                                                    }
                                                                }
                                                            }

                                                            customerDao.update(top4Customer);
                                                        }

                                                        if(top4Customer.getParentId() != null && top4Customer.getParentId() != 1198 && top4Customer.getLevelCopyId() != 11){
                                                            // 判断再上一级是否满足升级 专员
                                                            Customer top5Customer = customerDao.queryById(top4Customer.getParentId());
                                                            if(top5Customer.getLevelCopyId() <= top4Customer.getLevelCopyId()){
                                                                List<Customer> list5 = customerDao.queryCustomerByLevelCopyId_supreme(5, top5Customer.getId()); // 5=至尊
                                                                int size5 = list5.size();
                                                                if(size5 >= 1){
                                                                    if(top5Customer.getLevelCopyId() == 5){
                                                                        top5Customer.setLevelCopyId(6); // 升级到专员

                                                                        // 同步拼团等级
                                                                        top5Customer.setLevelId(6);
                                                                        if("0".equals(top5Customer.getIsActive())){
                                                                            // 是否购买过拼团产品
                                                                            List<Orders> ordersList = ordersDao.queryOrdersByUserIdIsBuyCollage(top5Customer.getId());
                                                                            if(ordersList.size() > 0){
                                                                                top5Customer.setIsActive("1"); // 激活拼团等级
                                                                            }
                                                                        }
                                                                        // TODO 直播等级 等待完善
                                                                        // 同步直播等级
                                                                        top5Customer.setLevelCopy1Id(6);
                                                                        // 判断是否购买过直播产品，买过就激活
                                                                        top5Customer.setIsActiveCopy1("0"); // 待激活直播等级

                                                                        // 同步蜜淘等级
                                                                        top5Customer.setLevelCopy2Id(6);
                                                                        if("0".equals(top5Customer.getIsActiveCopy2())){
                                                                            // 是否购买过蜜淘产品
                                                                            List<GoodsOrders> ordersList = goodsOrdersDao.queryGoodsOrdersByUserIdIsBuyBeeAmoy(top5Customer.getId());
                                                                            if(ordersList.size() > 0){
                                                                                top5Customer.setIsActive("1"); // 激活蜜淘等级
                                                                                if(top5Customer.getAddUpUpgrade().doubleValue() < 200000){
                                                                                    top5Customer.setAddUpUpgradeFiction(BigDecimal.valueOf(200000).subtract(top5Customer.getAddUpUpgrade()).add(top5Customer.getAddUpUpgradeFiction()));
                                                                                }
                                                                            }
                                                                        }

                                                                        customerDao.update(top5Customer);
                                                                    }

                                                                    if(top5Customer.getParentId() != null && top5Customer.getParentId() != 1198 && top5Customer.getLevelCopyId() != 11){
                                                                        // 判断再上一级是否满足升级 主管
                                                                        Customer top6Customer = customerDao.queryById(top5Customer.getParentId());
                                                                        if(top6Customer.getLevelCopyId() <= top5Customer.getLevelCopyId()){
                                                                            List<Customer> list6 = customerDao.queryCustomerByLevelCopyId_supreme(5, top6Customer.getId()); // 5=至尊
                                                                            int size6 = list6.size();
                                                                            if(size6 >= 2){
                                                                                if(top6Customer.getLevelCopyId() >= 5 && top6Customer.getLevelCopyId() < 7){
                                                                                    top6Customer.setLevelCopyId(7); // 升级到主管

                                                                                    // 同步拼团等级
                                                                                    top6Customer.setLevelId(6);
                                                                                    if("0".equals(top6Customer.getIsActive())){
                                                                                        // 是否购买过拼团产品
                                                                                        List<Orders> ordersList = ordersDao.queryOrdersByUserIdIsBuyCollage(top6Customer.getId());
                                                                                        if(ordersList.size() > 0){
                                                                                            top6Customer.setIsActive("1"); // 激活拼团等级
                                                                                        }
                                                                                    }
                                                                                    // TODO 直播等级 等待完善
                                                                                    // 同步直播等级
                                                                                    top6Customer.setLevelCopy1Id(6);
                                                                                    // 判断是否购买过直播产品，买过就激活
                                                                                    top6Customer.setIsActiveCopy1("0"); // 待激活直播等级

                                                                                    // 同步蜜淘等级
                                                                                    top6Customer.setLevelCopy2Id(6);
                                                                                    if("0".equals(top6Customer.getIsActiveCopy2())){
                                                                                        // 是否购买过蜜淘产品
                                                                                        List<GoodsOrders> ordersList = goodsOrdersDao.queryGoodsOrdersByUserIdIsBuyBeeAmoy(top6Customer.getId());
                                                                                        if(ordersList.size() > 0){
                                                                                            top6Customer.setIsActive("1"); // 激活蜜淘等级
                                                                                            if(top6Customer.getAddUpUpgrade().doubleValue() < 200000){
                                                                                                top6Customer.setAddUpUpgradeFiction(BigDecimal.valueOf(200000).subtract(top6Customer.getAddUpUpgrade()).add(top6Customer.getAddUpUpgradeFiction()));
                                                                                            }
                                                                                        }
                                                                                    }

                                                                                    customerDao.update(top6Customer);
                                                                                }

                                                                                if(top6Customer.getParentId() != null && top6Customer.getParentId() != 1198 && top6Customer.getLevelCopyId() != 11){
                                                                                    // 判断再上一级是否满足升级 经理
                                                                                    Customer top7Customer = customerDao.queryById(top6Customer.getParentId());
                                                                                    if(top7Customer.getLevelCopyId() <= top6Customer.getLevelCopyId()){
                                                                                        List<Customer> list7 = customerDao.queryCustomerByLevelCopyId_supreme(5, top7Customer.getId()); // 5=至尊
                                                                                        int size7 = list7.size();
                                                                                        if(size7 >= 3){
                                                                                            if(top7Customer.getLevelCopyId() >= 5 && top7Customer.getLevelCopyId() < 8){
                                                                                                top7Customer.setLevelCopyId(8); // 升级到经理

                                                                                                // 同步拼团等级
                                                                                                top7Customer.setLevelId(6);
                                                                                                if("0".equals(top7Customer.getIsActive())){
                                                                                                    // 是否购买过拼团产品
                                                                                                    List<Orders> ordersList = ordersDao.queryOrdersByUserIdIsBuyCollage(top7Customer.getId());
                                                                                                    if(ordersList.size() > 0){
                                                                                                        top7Customer.setIsActive("1"); // 激活拼团等级
                                                                                                    }
                                                                                                }
                                                                                                // TODO 直播等级 等待完善
                                                                                                // 同步直播等级
                                                                                                top7Customer.setLevelCopy1Id(6);
                                                                                                // 判断是否购买过直播产品，买过就激活
                                                                                                top7Customer.setIsActiveCopy1("0"); // 待激活直播等级

                                                                                                // 同步蜜淘等级
                                                                                                top7Customer.setLevelCopy2Id(6);
                                                                                                if("0".equals(top7Customer.getIsActiveCopy2())){
                                                                                                    // 是否购买过蜜淘产品
                                                                                                    List<GoodsOrders> ordersList = goodsOrdersDao.queryGoodsOrdersByUserIdIsBuyBeeAmoy(top7Customer.getId());
                                                                                                    if(ordersList.size() > 0){
                                                                                                        top7Customer.setIsActive("1"); // 激活蜜淘等级
                                                                                                        if(top7Customer.getAddUpUpgrade().doubleValue() < 200000){
                                                                                                            top7Customer.setAddUpUpgradeFiction(BigDecimal.valueOf(200000).subtract(top7Customer.getAddUpUpgrade()).add(top7Customer.getAddUpUpgradeFiction()));
                                                                                                        }
                                                                                                    }
                                                                                                }

                                                                                                customerDao.update(top7Customer);
                                                                                            }

                                                                                            if(top7Customer.getParentId() != null && top7Customer.getParentId() != 1198 && top7Customer.getLevelCopyId() != 11){
                                                                                                // 判断再上一级是否满足升级 总监
                                                                                                Customer top8Customer = customerDao.queryById(top7Customer.getParentId());
                                                                                                if(top8Customer.getLevelCopyId() <= top7Customer.getLevelCopyId()){
                                                                                                    List<Customer> list8 = customerDao.queryCustomerByLevelCopyId_supreme(5, top8Customer.getId()); // 5=至尊
                                                                                                    int size8 = list8.size();
                                                                                                    if(size8 >= 6){
                                                                                                        if(top8Customer.getLevelCopyId() >= 5 && top8Customer.getLevelCopyId() < 9){
                                                                                                            top8Customer.setLevelCopyId(9); // 升级到总监

                                                                                                            // 同步拼团等级
                                                                                                            top8Customer.setLevelId(6);
                                                                                                            if("0".equals(top8Customer.getIsActive())){
                                                                                                                // 是否购买过拼团产品
                                                                                                                List<Orders> ordersList = ordersDao.queryOrdersByUserIdIsBuyCollage(top8Customer.getId());
                                                                                                                if(ordersList.size() > 0){
                                                                                                                    top8Customer.setIsActive("1"); // 激活拼团等级
                                                                                                                }
                                                                                                            }
                                                                                                            // TODO 直播等级 等待完善
                                                                                                            // 同步直播等级
                                                                                                            top8Customer.setLevelCopy1Id(6);
                                                                                                            // 判断是否购买过直播产品，买过就激活
                                                                                                            top8Customer.setIsActiveCopy1("0"); // 待激活直播等级

                                                                                                            // 同步蜜淘等级
                                                                                                            top8Customer.setLevelCopy2Id(6);
                                                                                                            if("0".equals(top8Customer.getIsActiveCopy2())){
                                                                                                                // 是否购买过蜜淘产品
                                                                                                                List<GoodsOrders> ordersList = goodsOrdersDao.queryGoodsOrdersByUserIdIsBuyBeeAmoy(top8Customer.getId());
                                                                                                                if(ordersList.size() > 0){
                                                                                                                    top8Customer.setIsActive("1"); // 激活蜜淘等级
                                                                                                                    if(top8Customer.getAddUpUpgrade().doubleValue() < 200000){
                                                                                                                        top8Customer.setAddUpUpgradeFiction(BigDecimal.valueOf(200000).subtract(top8Customer.getAddUpUpgrade()).add(top8Customer.getAddUpUpgradeFiction()));
                                                                                                                    }
                                                                                                                }
                                                                                                            }

                                                                                                            customerDao.update(top8Customer);
                                                                                                        }

                                                                                                        if(top8Customer.getParentId() != null && top8Customer.getParentId() != 1198 && top8Customer.getLevelCopyId() != 11){
                                                                                                            // 判断再上一级是否满足升级 总裁
                                                                                                            Customer top9Customer = customerDao.queryById(top8Customer.getParentId());
                                                                                                            if(top9Customer.getLevelCopyId() <= top8Customer.getLevelCopyId()){
                                                                                                                // 查看直推的人是否达到5个至尊
                                                                                                                List<Customer> list9 = customerDao.queryCustomerByLevelCopyId_supreme(5, top9Customer.getId());
                                                                                                                int size9 = list9.size();
                                                                                                                if(size9 >= 9) { // 有就直接升级
                                                                                                                    if(top9Customer.getLevelCopyId() >= 5 && top9Customer.getLevelCopyId() < 10){
                                                                                                                        top9Customer.setLevelCopyId(10); // 升级到总裁

                                                                                                                        // 同步拼团等级
                                                                                                                        top9Customer.setLevelId(6);
                                                                                                                        if("0".equals(top9Customer.getIsActive())){
                                                                                                                            // 是否购买过拼团产品
                                                                                                                            List<Orders> ordersList = ordersDao.queryOrdersByUserIdIsBuyCollage(top9Customer.getId());
                                                                                                                            if(ordersList.size() > 0){
                                                                                                                                top9Customer.setIsActive("1"); // 激活拼团等级
                                                                                                                            }
                                                                                                                        }
                                                                                                                        // TODO 直播等级 等待完善
                                                                                                                        // 同步直播等级
                                                                                                                        top9Customer.setLevelCopy1Id(6);
                                                                                                                        // 判断是否购买过直播产品，买过就激活
                                                                                                                        top9Customer.setIsActiveCopy1("0"); // 待激活直播等级

                                                                                                                        // 同步蜜淘等级
                                                                                                                        top9Customer.setLevelCopy2Id(6);
                                                                                                                        if("0".equals(top9Customer.getIsActiveCopy2())){
                                                                                                                            // 是否购买过蜜淘产品
                                                                                                                            List<GoodsOrders> ordersList = goodsOrdersDao.queryGoodsOrdersByUserIdIsBuyBeeAmoy(top9Customer.getId());
                                                                                                                            if(ordersList.size() > 0){
                                                                                                                                top9Customer.setIsActive("1"); // 激活蜜淘等级
                                                                                                                                if(top9Customer.getAddUpUpgrade().doubleValue() < 200000){
                                                                                                                                    top9Customer.setAddUpUpgradeFiction(BigDecimal.valueOf(200000).subtract(top9Customer.getAddUpUpgrade()).add(top9Customer.getAddUpUpgradeFiction()));
                                                                                                                                }
                                                                                                                            }
                                                                                                                        }

                                                                                                                        customerDao.update(top9Customer);
                                                                                                                    }
                                                                                                                }else{ // 没有就找人
                                                                                                                    List<Customer> queryList9 = customerDao.queryCustomerByLevelCopyId1(5, top9Customer.getId()); // top9的直推,等级小于至尊的
                                                                                                                    if(queryList9.size() > 0){
                                                                                                                        int index9 = size9;
                                                                                                                        for (Customer c9 : queryList9) {
                                                                                                                            // 为top9寻找至尊 当前子级下是否存在至尊
                                                                                                                            int temp = customerService.recursionCustomer(5, c9.getId());
                                                                                                                            if(temp > 0){
                                                                                                                                c9.setSupreme("1");
                                                                                                                                customerDao.update(c9);
                                                                                                                            }
                                                                                                                            index9 += temp;
                                                                                                                            if (index9 >= 9) {
                                                                                                                                if(top9Customer.getLevelCopyId() >= 5 && top9Customer.getLevelCopyId() < 10){
                                                                                                                                    top9Customer.setLevelCopyId(10); // 升级到总裁

                                                                                                                                    // 同步拼团等级
                                                                                                                                    top9Customer.setLevelId(6);
                                                                                                                                    if("0".equals(top9Customer.getIsActive())){
                                                                                                                                        // 是否购买过拼团产品
                                                                                                                                        List<Orders> ordersList = ordersDao.queryOrdersByUserIdIsBuyCollage(top9Customer.getId());
                                                                                                                                        if(ordersList.size() > 0){
                                                                                                                                            top9Customer.setIsActive("1"); // 激活拼团等级
                                                                                                                                        }
                                                                                                                                    }
                                                                                                                                    // TODO 直播等级 等待完善
                                                                                                                                    // 同步直播等级
                                                                                                                                    top9Customer.setLevelCopy1Id(6);
                                                                                                                                    // 判断是否购买过直播产品，买过就激活
                                                                                                                                    top9Customer.setIsActiveCopy1("0"); // 待激活直播等级

                                                                                                                                    // 同步蜜淘等级
                                                                                                                                    top9Customer.setLevelCopy2Id(6);
                                                                                                                                    if("0".equals(top9Customer.getIsActiveCopy2())){
                                                                                                                                        // 是否购买过蜜淘产品
                                                                                                                                        List<GoodsOrders> ordersList = goodsOrdersDao.queryGoodsOrdersByUserIdIsBuyBeeAmoy(top9Customer.getId());
                                                                                                                                        if(ordersList.size() > 0){
                                                                                                                                            top9Customer.setIsActive("1"); // 激活蜜淘等级
                                                                                                                                            if(top9Customer.getAddUpUpgrade().doubleValue() < 200000){
                                                                                                                                                top9Customer.setAddUpUpgradeFiction(BigDecimal.valueOf(200000).subtract(top9Customer.getAddUpUpgrade()).add(top9Customer.getAddUpUpgradeFiction()));
                                                                                                                                            }
                                                                                                                                        }
                                                                                                                                    }

                                                                                                                                    customerDao.update(top9Customer);
                                                                                                                                }
                                                                                                                                break;
                                                                                                                            }
                                                                                                                        }
                                                                                                                    }
                                                                                                                }
                                                                                                            }
                                                                                                        }
                                                                                                    }else{
                                                                                                        List<Customer> queryList8 = customerDao.queryCustomerByLevelCopyId1(5, top8Customer.getId());
                                                                                                        if(queryList8.size() > 0){
                                                                                                            int index8 = size8;
                                                                                                            for (Customer c8 : queryList8) {
                                                                                                                int temp = customerService.recursionCustomer(5, c8.getId());
                                                                                                                if(temp > 0){
                                                                                                                    c8.setSupreme("1");
                                                                                                                    customerDao.update(c8);
                                                                                                                }
                                                                                                                index8 += temp;
                                                                                                                if (index8 >= 6) {
                                                                                                                    if(top8Customer.getLevelCopyId() >= 5 && top8Customer.getLevelCopyId() < 9){
                                                                                                                        top8Customer.setLevelCopyId(9); // 升级到总监

                                                                                                                        // 同步拼团等级
                                                                                                                        top8Customer.setLevelId(6);
                                                                                                                        if("0".equals(top8Customer.getIsActive())){
                                                                                                                            // 是否购买过拼团产品
                                                                                                                            List<Orders> ordersList = ordersDao.queryOrdersByUserIdIsBuyCollage(top8Customer.getId());
                                                                                                                            if(ordersList.size() > 0){
                                                                                                                                top8Customer.setIsActive("1"); // 激活拼团等级
                                                                                                                            }
                                                                                                                        }
                                                                                                                        // TODO 直播等级 等待完善
                                                                                                                        // 同步直播等级
                                                                                                                        top8Customer.setLevelCopy1Id(6);
                                                                                                                        // 判断是否购买过直播产品，买过就激活
                                                                                                                        top8Customer.setIsActiveCopy1("0"); // 待激活直播等级

                                                                                                                        // 同步蜜淘等级
                                                                                                                        top8Customer.setLevelCopy2Id(6);
                                                                                                                        if("0".equals(top8Customer.getIsActiveCopy2())){
                                                                                                                            // 是否购买过蜜淘产品
                                                                                                                            List<GoodsOrders> ordersList = goodsOrdersDao.queryGoodsOrdersByUserIdIsBuyBeeAmoy(top8Customer.getId());
                                                                                                                            if(ordersList.size() > 0){
                                                                                                                                top8Customer.setIsActive("1"); // 激活蜜淘等级
                                                                                                                                if(top8Customer.getAddUpUpgrade().doubleValue() < 200000){
                                                                                                                                    top8Customer.setAddUpUpgradeFiction(BigDecimal.valueOf(200000).subtract(top8Customer.getAddUpUpgrade()).add(top8Customer.getAddUpUpgradeFiction()));
                                                                                                                                }
                                                                                                                            }
                                                                                                                        }

                                                                                                                        customerDao.update(top8Customer);
                                                                                                                    }
                                                                                                                    break;
                                                                                                                }
                                                                                                            }
                                                                                                        }
                                                                                                    }
                                                                                                }
                                                                                            }
                                                                                        }else{
                                                                                            List<Customer> queryList7 = customerDao.queryCustomerByLevelCopyId1(5, top7Customer.getId());
                                                                                            if(queryList7.size() > 0){
                                                                                                int index7 = size7;
                                                                                                for (Customer c7 : queryList7) {
                                                                                                    int temp = customerService.recursionCustomer(5, c7.getId());
                                                                                                    if(temp > 0){
                                                                                                        c7.setSupreme("1");
                                                                                                        customerDao.update(c7);
                                                                                                    }
                                                                                                    index7 += temp;
                                                                                                    if (index7 >= 3) {
                                                                                                        if(top7Customer.getLevelCopyId() >= 5 && top7Customer.getLevelCopyId() < 8){
                                                                                                            top7Customer.setLevelCopyId(8); // 升级到经理

                                                                                                            // 同步拼团等级
                                                                                                            top7Customer.setLevelId(6);
                                                                                                            if("0".equals(top7Customer.getIsActive())){
                                                                                                                // 是否购买过拼团产品
                                                                                                                List<Orders> ordersList = ordersDao.queryOrdersByUserIdIsBuyCollage(top7Customer.getId());
                                                                                                                if(ordersList.size() > 0){
                                                                                                                    top7Customer.setIsActive("1"); // 激活拼团等级
                                                                                                                }
                                                                                                            }
                                                                                                            // TODO 直播等级 等待完善
                                                                                                            // 同步直播等级
                                                                                                            top7Customer.setLevelCopy1Id(6);
                                                                                                            // 判断是否购买过直播产品，买过就激活
                                                                                                            top7Customer.setIsActiveCopy1("0"); // 待激活直播等级

                                                                                                            // 同步蜜淘等级
                                                                                                            top7Customer.setLevelCopy2Id(6);
                                                                                                            if("0".equals(top7Customer.getIsActiveCopy2())){
                                                                                                                // 是否购买过蜜淘产品
                                                                                                                List<GoodsOrders> ordersList = goodsOrdersDao.queryGoodsOrdersByUserIdIsBuyBeeAmoy(top7Customer.getId());
                                                                                                                if(ordersList.size() > 0){
                                                                                                                    top7Customer.setIsActive("1"); // 激活蜜淘等级
                                                                                                                    if(top7Customer.getAddUpUpgrade().doubleValue() < 200000){
                                                                                                                        top7Customer.setAddUpUpgradeFiction(BigDecimal.valueOf(200000).subtract(top7Customer.getAddUpUpgrade()).add(top7Customer.getAddUpUpgradeFiction()));
                                                                                                                    }
                                                                                                                }
                                                                                                            }

                                                                                                            customerDao.update(top7Customer);
                                                                                                        }
                                                                                                        break;
                                                                                                    }
                                                                                                }
                                                                                            }
                                                                                        }
                                                                                    }
                                                                                }
                                                                            }else{
                                                                                List<Customer> queryList6 = customerDao.queryCustomerByLevelCopyId1(5, top6Customer.getId());
                                                                                if(queryList6.size() > 0){
                                                                                    int index6 = size6;
                                                                                    for (Customer c6 : queryList6) {
                                                                                        int temp = customerService.recursionCustomer(5, c6.getId());
                                                                                        if(temp > 0){
                                                                                            c6.setSupreme("1");
                                                                                            customerDao.update(c6);
                                                                                        }
                                                                                        index6 += temp;
                                                                                        if (index6 >= 2) {
                                                                                            if(top6Customer.getLevelCopyId() >= 5 && top6Customer.getLevelCopyId() < 7){
                                                                                                top6Customer.setLevelCopyId(7); // 升级到主管

                                                                                                // 同步拼团等级
                                                                                                top6Customer.setLevelId(6);
                                                                                                if("0".equals(top6Customer.getIsActive())){
                                                                                                    // 是否购买过拼团产品
                                                                                                    List<Orders> ordersList = ordersDao.queryOrdersByUserIdIsBuyCollage(top6Customer.getId());
                                                                                                    if(ordersList.size() > 0){
                                                                                                        top6Customer.setIsActive("1"); // 激活拼团等级
                                                                                                    }
                                                                                                }
                                                                                                // TODO 直播等级 等待完善
                                                                                                // 同步直播等级
                                                                                                top6Customer.setLevelCopy1Id(6);
                                                                                                // 判断是否购买过直播产品，买过就激活
                                                                                                top6Customer.setIsActiveCopy1("0"); // 待激活直播等级

                                                                                                // 同步蜜淘等级
                                                                                                top6Customer.setLevelCopy2Id(6);
                                                                                                if("0".equals(top6Customer.getIsActiveCopy2())){
                                                                                                    // 是否购买过蜜淘产品
                                                                                                    List<GoodsOrders> ordersList = goodsOrdersDao.queryGoodsOrdersByUserIdIsBuyBeeAmoy(top6Customer.getId());
                                                                                                    if(ordersList.size() > 0){
                                                                                                        top6Customer.setIsActive("1"); // 激活蜜淘等级
                                                                                                        if(top6Customer.getAddUpUpgrade().doubleValue() < 200000){
                                                                                                            top6Customer.setAddUpUpgradeFiction(BigDecimal.valueOf(200000).subtract(top6Customer.getAddUpUpgrade()).add(top6Customer.getAddUpUpgradeFiction()));
                                                                                                        }
                                                                                                    }
                                                                                                }

                                                                                                customerDao.update(top6Customer);
                                                                                            }
                                                                                            break;
                                                                                        }
                                                                                    }
                                                                                }
                                                                            }
                                                                        }
                                                                    }
                                                                }else{
                                                                    List<Customer> queryList5 = customerDao.queryCustomerByLevelCopyId1(5, top5Customer.getId());
                                                                    if(queryList5.size() > 0){
                                                                        int index5 = size5;
                                                                        for (Customer c5 : queryList5) {
                                                                            int temp = customerService.recursionCustomer(5, c5.getId());
                                                                            if(temp > 0){
                                                                                c5.setSupreme("1");
                                                                                customerDao.update(c5);
                                                                            }
                                                                            index5 += temp;
                                                                            if (index5 >= 1) {
                                                                                if(top5Customer.getLevelCopyId() >= 5 && top5Customer.getLevelCopyId() < 6){
                                                                                    top5Customer.setLevelCopyId(6); // 升级到专员

                                                                                    // 同步拼团等级
                                                                                    top5Customer.setLevelId(6);
                                                                                    if("0".equals(top5Customer.getIsActive())){
                                                                                        // 是否购买过拼团产品
                                                                                        List<Orders> ordersList = ordersDao.queryOrdersByUserIdIsBuyCollage(top5Customer.getId());
                                                                                        if(ordersList.size() > 0){
                                                                                            top5Customer.setIsActive("1"); // 激活拼团等级
                                                                                        }
                                                                                    }
                                                                                    // TODO 直播等级 等待完善
                                                                                    // 同步直播等级
                                                                                    top5Customer.setLevelCopy1Id(6);
                                                                                    // 判断是否购买过直播产品，买过就激活
                                                                                    top5Customer.setIsActiveCopy1("0"); // 待激活直播等级

                                                                                    // 同步蜜淘等级
                                                                                    top5Customer.setLevelCopy2Id(6);
                                                                                    if("0".equals(top5Customer.getIsActiveCopy2())){
                                                                                        // 是否购买过蜜淘产品
                                                                                        List<GoodsOrders> ordersList = goodsOrdersDao.queryGoodsOrdersByUserIdIsBuyBeeAmoy(top5Customer.getId());
                                                                                        if(ordersList.size() > 0){
                                                                                            top5Customer.setIsActive("1"); // 激活蜜淘等级
                                                                                            if(top5Customer.getAddUpUpgrade().doubleValue() < 200000){
                                                                                                top5Customer.setAddUpUpgradeFiction(BigDecimal.valueOf(200000).subtract(top5Customer.getAddUpUpgrade()).add(top5Customer.getAddUpUpgradeFiction()));
                                                                                            }
                                                                                        }
                                                                                    }

                                                                                    customerDao.update(top5Customer);
                                                                                }
                                                                                break;
                                                                            }
                                                                        }
                                                                    }
                                                                }
                                                            }
                                                        }
                                                    }else {
                                                        List<Customer> queryList4 = customerDao.queryCustomerByLevelCopyId1(4, top4Customer.getId());
                                                        if(queryList4.size() > 0){
                                                            int index4 = size4;
                                                            for (Customer c4 : queryList4) {
                                                                int temp = customerService.recursionCustomer(4, c4.getId());
                                                                if(temp > 0){
                                                                    c4.setTheKing("1");
                                                                    customerDao.update(c4);
                                                                }
                                                                index4 += temp;
                                                                if (index4 >= 3) {
                                                                    if(top4Customer.getLevelCopyId() > 1){
                                                                        top4Customer.setLevelCopyId(5); // 升级到至尊

                                                                        // 同步拼团等级
                                                                        top4Customer.setLevelId(5);
                                                                        if("0".equals(top4Customer.getIsActive())){
                                                                            // 是否购买过拼团产品
                                                                            List<Orders> ordersList = ordersDao.queryOrdersByUserIdIsBuyCollage(top4Customer.getId());
                                                                            if(ordersList.size() > 0){
                                                                                top4Customer.setIsActive("1"); // 激活拼团等级
                                                                            }
                                                                        }
                                                                        // TODO 直播等级 等待完善
                                                                        // 同步直播等级
                                                                        top4Customer.setLevelCopy1Id(5);
                                                                        // 判断是否购买过直播产品，买过就激活
                                                                        top4Customer.setIsActiveCopy1("0"); // 待激活直播等级

                                                                        // 同步蜜淘等级
                                                                        top4Customer.setLevelCopy2Id(5);
                                                                        if("0".equals(top4Customer.getIsActiveCopy2())){
                                                                            // 是否购买过蜜淘产品
                                                                            List<GoodsOrders> ordersList = goodsOrdersDao.queryGoodsOrdersByUserIdIsBuyBeeAmoy(top4Customer.getId());
                                                                            if(ordersList.size() > 0){
                                                                                top4Customer.setIsActive("1"); // 激活蜜淘等级
                                                                                if(top4Customer.getAddUpUpgrade().doubleValue() < 100000){
                                                                                    top4Customer.setAddUpUpgradeFiction(BigDecimal.valueOf(100000).subtract(top4Customer.getAddUpUpgrade()).add(top4Customer.getAddUpUpgradeFiction()));
                                                                                }
                                                                            }
                                                                        }

                                                                        customerDao.update(top4Customer);
                                                                    }
                                                                    break;
                                                                }
                                                            }
                                                        }
                                                    }
                                                }
                                            }
                                        }else{
                                            List<Customer> queryList3 = customerDao.queryCustomerByLevelCopyId1(3, top3Customer.getId());
                                            if(queryList3.size() > 0){
                                                int index3 = size3;
                                                for (Customer c3 : queryList3) {
                                                    int temp = customerService.recursionCustomer(3, c3.getId());
                                                    if(temp > 0){
                                                        c3.setKiller("1");
                                                        customerDao.update(c3);
                                                    }
                                                    index3 += temp;
                                                    if (index3 >= 6) {
                                                        if(top3Customer.getLevelCopyId() > 1){
                                                            top3Customer.setLevelCopyId(4); // 升级到王者

                                                            // 同步拼团等级
                                                            top3Customer.setLevelId(4);
                                                            if("0".equals(top3Customer.getIsActive())){
                                                                // 是否购买过拼团产品
                                                                List<Orders> ordersList = ordersDao.queryOrdersByUserIdIsBuyCollage(top3Customer.getId());
                                                                if(ordersList.size() > 0){
                                                                    top3Customer.setIsActive("1"); // 激活拼团等级
                                                                }
                                                            }
                                                            // TODO 直播等级 等待完善
                                                            // 同步直播等级
                                                            top3Customer.setLevelCopy1Id(4);
                                                            // 判断是否购买过直播产品，买过就激活
                                                            top3Customer.setIsActiveCopy1("0"); // 待激活直播等级

                                                            // 同步蜜淘等级
                                                            top3Customer.setLevelCopy2Id(4);
                                                            if("0".equals(top3Customer.getIsActiveCopy2())){
                                                                // 是否购买过蜜淘产品
                                                                List<GoodsOrders> ordersList = goodsOrdersDao.queryGoodsOrdersByUserIdIsBuyBeeAmoy(top3Customer.getId());
                                                                if(ordersList.size() > 0){
                                                                    top3Customer.setIsActive("1"); // 激活蜜淘等级
                                                                    if(top3Customer.getAddUpUpgrade().doubleValue() < 50000){
                                                                        top3Customer.setAddUpUpgradeFiction(BigDecimal.valueOf(50000).subtract(top3Customer.getAddUpUpgrade()).add(top3Customer.getAddUpUpgradeFiction()));
                                                                    }
                                                                }
                                                            }

                                                            customerDao.update(top3Customer);
                                                        }
                                                        break;
                                                    }
                                                }
                                            }
                                        }
                                    }
                                }
                            }
                        }else{
                            // 必须为上级直推了9个菜鸟才能升级到高手
                        }
                    }
                }

            }
            // 3690礼包
            else if(totalAmount >= 3690 && totalAmount < 36900){

                if(customer.getLevelCopyId() < 3){
                    customer.setLevelCopyId(3); // 升级为高手
                    if("0".equals(customer.getIsActiveCopy())){
                        customer.setIsActiveCopy("1"); // 激活共享等级
                    }
                    // 同步拼团等级
                    customer.setLevelId(3);
                    if("0".equals(customer.getIsActive())){
                        // 是否购买过拼团产品
                        List<Orders> ordersList = ordersDao.queryOrdersByUserIdIsBuyCollage(customer.getId());
                        if(ordersList.size() > 0){
                            customer.setIsActive("1"); // 激活拼团等级
                        }
                    }
                    // TODO 直播等级 等待完善
                    // 同步直播等级
                    customer.setLevelCopy1Id(3);
                    // 判断是否购买过直播产品，买过就激活
                    customer.setIsActiveCopy1("0"); // 待激活直播等级

                    // 同步蜜淘等级
                    customer.setLevelCopy2Id(3);
                    if("0".equals(customer.getIsActiveCopy2())){
                        // 是否购买过蜜淘产品
                        List<GoodsOrders> ordersList = goodsOrdersDao.queryGoodsOrdersByUserIdIsBuyBeeAmoy(customer.getId());
                        if(ordersList.size() > 0){
                            customer.setIsActive("1"); // 激活蜜淘等级
                            if(customer.getAddUpUpgrade().doubleValue() < 10000){
                                customer.setAddUpUpgradeFiction(BigDecimal.valueOf(10000).subtract(customer.getAddUpUpgrade()).add(customer.getAddUpUpgradeFiction()));
                            }
                        }
                    }

                    customerDao.update(customer);

                    if(customer.getParentId() != null && customer.getParentId() != 1198 && customer.getLevelCopyId() != 11){
                        // 判断再上一级是否满足升级 王者
                        Customer top3Customer = customerDao.queryById(customer.getParentId());
                        if(top3Customer.getLevelCopyId() <= customer.getLevelCopyId()){
                            List<Customer> list3 = customerDao.queryCustomerByLevelCopyId_killer(3, top3Customer.getId()); // 3=高手
                            int size3 = list3.size();
                            if(size3 >= 6){
                                if(top3Customer.getLevelCopyId() > 1){
                                    top3Customer.setLevelCopyId(4); // 升级为王者

                                    // 同步拼团等级
                                    top3Customer.setLevelId(4);
                                    if("0".equals(top3Customer.getIsActive())){
                                        // 是否购买过拼团产品
                                        List<Orders> ordersList = ordersDao.queryOrdersByUserIdIsBuyCollage(top3Customer.getId());
                                        if(ordersList.size() > 0){
                                            top3Customer.setIsActive("1"); // 激活拼团等级
                                        }
                                    }
                                    // TODO 直播等级 等待完善
                                    // 同步直播等级
                                    top3Customer.setLevelCopy1Id(4);
                                    // 判断是否购买过直播产品，买过就激活
                                    top3Customer.setIsActiveCopy1("0"); // 待激活直播等级

                                    // 同步蜜淘等级
                                    top3Customer.setLevelCopy2Id(4);
                                    if("0".equals(top3Customer.getIsActiveCopy2())){
                                        // 是否购买过蜜淘产品
                                        List<GoodsOrders> ordersList = goodsOrdersDao.queryGoodsOrdersByUserIdIsBuyBeeAmoy(top3Customer.getId());
                                        if(ordersList.size() > 0){
                                            top3Customer.setIsActive("1"); // 激活蜜淘等级
                                            if(top3Customer.getAddUpUpgrade().doubleValue() < 50000){
                                                top3Customer.setAddUpUpgradeFiction(BigDecimal.valueOf(50000).subtract(top3Customer.getAddUpUpgrade()).add(top3Customer.getAddUpUpgradeFiction()));
                                            }
                                        }
                                    }

                                    customerDao.update(top3Customer);
                                }

                                if(top3Customer.getParentId() != null && top3Customer.getParentId() != 1198 && top3Customer.getLevelCopyId() != 11){
                                    // 判断再上一级是否满足升级 至尊
                                    Customer top4Customer = customerDao.queryById(top3Customer.getParentId());
                                    if(top4Customer.getLevelCopyId() <= top3Customer.getLevelCopyId()){
                                        List<Customer> list4 = customerDao.queryCustomerByLevelCopyId_theKing(4, top4Customer.getId()); // 4=王者
                                        int size4 = list4.size();
                                        if(size4 >= 3){
                                            if(top4Customer.getLevelCopyId() > 1) {
                                                top4Customer.setLevelCopyId(5); // 升级到至尊

                                                // 同步拼团等级
                                                top4Customer.setLevelId(5);
                                                if("0".equals(top4Customer.getIsActive())){
                                                    // 是否购买过拼团产品
                                                    List<Orders> ordersList = ordersDao.queryOrdersByUserIdIsBuyCollage(top4Customer.getId());
                                                    if(ordersList.size() > 0){
                                                        top4Customer.setIsActive("1"); // 激活拼团等级
                                                    }
                                                }
                                                // TODO 直播等级 等待完善
                                                // 同步直播等级
                                                top4Customer.setLevelCopy1Id(5);
                                                // 判断是否购买过直播产品，买过就激活
                                                top4Customer.setIsActiveCopy1("0"); // 待激活直播等级

                                                // 同步蜜淘等级
                                                top4Customer.setLevelCopy2Id(5);
                                                if("0".equals(top4Customer.getIsActiveCopy2())){
                                                    // 是否购买过蜜淘产品
                                                    List<GoodsOrders> ordersList = goodsOrdersDao.queryGoodsOrdersByUserIdIsBuyBeeAmoy(top4Customer.getId());
                                                    if(ordersList.size() > 0){
                                                        top4Customer.setIsActive("1"); // 激活蜜淘等级
                                                        if(top4Customer.getAddUpUpgrade().doubleValue() < 100000){
                                                            top4Customer.setAddUpUpgradeFiction(BigDecimal.valueOf(100000).subtract(top4Customer.getAddUpUpgrade()).add(top4Customer.getAddUpUpgradeFiction()));
                                                        }
                                                    }
                                                }

                                                customerDao.update(top4Customer);
                                            }

                                            if(top4Customer.getParentId() != null && top4Customer.getParentId() != 1198 && top4Customer.getLevelCopyId() != 11){
                                                // 判断再上一级是否满足升级 专员
                                                Customer top5Customer = customerDao.queryById(top4Customer.getParentId());
                                                if(top5Customer.getLevelCopyId() <= top4Customer.getLevelCopyId()){
                                                    List<Customer> list5 = customerDao.queryCustomerByLevelCopyId_supreme(5, top5Customer.getId()); // 5=至尊
                                                    int size5 = list5.size();
                                                    if(size5 >= 1){
                                                        if(top5Customer.getLevelCopyId() == 5){
                                                            top5Customer.setLevelCopyId(6); // 升级到专员

                                                            // 同步拼团等级
                                                            top5Customer.setLevelId(6);
                                                            if("0".equals(top5Customer.getIsActive())){
                                                                // 是否购买过拼团产品
                                                                List<Orders> ordersList = ordersDao.queryOrdersByUserIdIsBuyCollage(top5Customer.getId());
                                                                if(ordersList.size() > 0){
                                                                    top5Customer.setIsActive("1"); // 激活拼团等级
                                                                }
                                                            }
                                                            // TODO 直播等级 等待完善
                                                            // 同步直播等级
                                                            top5Customer.setLevelCopy1Id(6);
                                                            // 判断是否购买过直播产品，买过就激活
                                                            top5Customer.setIsActiveCopy1("0"); // 待激活直播等级

                                                            // 同步蜜淘等级
                                                            top5Customer.setLevelCopy2Id(6);
                                                            if("0".equals(top5Customer.getIsActiveCopy2())){
                                                                // 是否购买过蜜淘产品
                                                                List<GoodsOrders> ordersList = goodsOrdersDao.queryGoodsOrdersByUserIdIsBuyBeeAmoy(top5Customer.getId());
                                                                if(ordersList.size() > 0){
                                                                    top5Customer.setIsActive("1"); // 激活蜜淘等级
                                                                    if(top5Customer.getAddUpUpgrade().doubleValue() < 200000){
                                                                        top5Customer.setAddUpUpgradeFiction(BigDecimal.valueOf(200000).subtract(top5Customer.getAddUpUpgrade()).add(top5Customer.getAddUpUpgradeFiction()));
                                                                    }
                                                                }
                                                            }

                                                            customerDao.update(top5Customer);
                                                        }

                                                        if(top5Customer.getParentId() != null && top5Customer.getParentId() != 1198 && top5Customer.getLevelCopyId() != 11){
                                                            // 判断再上一级是否满足升级 主管
                                                            Customer top6Customer = customerDao.queryById(top5Customer.getParentId());
                                                            if(top6Customer.getLevelCopyId() <= top5Customer.getLevelCopyId()){
                                                                List<Customer> list6 = customerDao.queryCustomerByLevelCopyId_supreme(5, top6Customer.getId()); // 5=至尊
                                                                int size6 = list6.size();
                                                                if(size6 >= 2){
                                                                    if(top6Customer.getLevelCopyId() >= 5 && top6Customer.getLevelCopyId() < 7){
                                                                        top6Customer.setLevelCopyId(7); // 升级到主管

                                                                        // 同步拼团等级
                                                                        top6Customer.setLevelId(6);
                                                                        if("0".equals(top6Customer.getIsActive())){
                                                                            // 是否购买过拼团产品
                                                                            List<Orders> ordersList = ordersDao.queryOrdersByUserIdIsBuyCollage(top6Customer.getId());
                                                                            if(ordersList.size() > 0){
                                                                                top6Customer.setIsActive("1"); // 激活拼团等级
                                                                            }
                                                                        }
                                                                        // TODO 直播等级 等待完善
                                                                        // 同步直播等级
                                                                        top6Customer.setLevelCopy1Id(6);
                                                                        // 判断是否购买过直播产品，买过就激活
                                                                        top6Customer.setIsActiveCopy1("0"); // 待激活直播等级

                                                                        // 同步蜜淘等级
                                                                        top6Customer.setLevelCopy2Id(6);
                                                                        if("0".equals(top6Customer.getIsActiveCopy2())){
                                                                            // 是否购买过蜜淘产品
                                                                            List<GoodsOrders> ordersList = goodsOrdersDao.queryGoodsOrdersByUserIdIsBuyBeeAmoy(top6Customer.getId());
                                                                            if(ordersList.size() > 0){
                                                                                top6Customer.setIsActive("1"); // 激活蜜淘等级
                                                                                if(top6Customer.getAddUpUpgrade().doubleValue() < 200000){
                                                                                    top6Customer.setAddUpUpgradeFiction(BigDecimal.valueOf(200000).subtract(top6Customer.getAddUpUpgrade()).add(top6Customer.getAddUpUpgradeFiction()));
                                                                                }
                                                                            }
                                                                        }

                                                                        customerDao.update(top6Customer);
                                                                    }

                                                                    if(top6Customer.getParentId() != null && top6Customer.getParentId() != 1198 && top6Customer.getLevelCopyId() != 11){
                                                                        // 判断再上一级是否满足升级 经理
                                                                        Customer top7Customer = customerDao.queryById(top6Customer.getParentId());
                                                                        if(top7Customer.getLevelCopyId() <= top6Customer.getLevelCopyId()){
                                                                            List<Customer> list7 = customerDao.queryCustomerByLevelCopyId_supreme(5, top7Customer.getId()); // 5=至尊
                                                                            int size7 = list7.size();
                                                                            if(size7 >= 3){
                                                                                if(top7Customer.getLevelCopyId() >= 5 && top7Customer.getLevelCopyId() < 8){
                                                                                    top7Customer.setLevelCopyId(8); // 升级到经理

                                                                                    // 同步拼团等级
                                                                                    top7Customer.setLevelId(6);
                                                                                    if("0".equals(top7Customer.getIsActive())){
                                                                                        // 是否购买过拼团产品
                                                                                        List<Orders> ordersList = ordersDao.queryOrdersByUserIdIsBuyCollage(top7Customer.getId());
                                                                                        if(ordersList.size() > 0){
                                                                                            top7Customer.setIsActive("1"); // 激活拼团等级
                                                                                        }
                                                                                    }
                                                                                    // TODO 直播等级 等待完善
                                                                                    // 同步直播等级
                                                                                    top7Customer.setLevelCopy1Id(6);
                                                                                    // 判断是否购买过直播产品，买过就激活
                                                                                    top7Customer.setIsActiveCopy1("0"); // 待激活直播等级

                                                                                    // 同步蜜淘等级
                                                                                    top7Customer.setLevelCopy2Id(6);
                                                                                    if("0".equals(top7Customer.getIsActiveCopy2())){
                                                                                        // 是否购买过蜜淘产品
                                                                                        List<GoodsOrders> ordersList = goodsOrdersDao.queryGoodsOrdersByUserIdIsBuyBeeAmoy(top7Customer.getId());
                                                                                        if(ordersList.size() > 0){
                                                                                            top7Customer.setIsActive("1"); // 激活蜜淘等级
                                                                                            if(top7Customer.getAddUpUpgrade().doubleValue() < 200000){
                                                                                                top7Customer.setAddUpUpgradeFiction(BigDecimal.valueOf(200000).subtract(top7Customer.getAddUpUpgrade()).add(top7Customer.getAddUpUpgradeFiction()));
                                                                                            }
                                                                                        }
                                                                                    }

                                                                                    customerDao.update(top7Customer);
                                                                                }

                                                                                if(top7Customer.getParentId() != null && top7Customer.getParentId() != 1198 && top7Customer.getLevelCopyId() != 11){
                                                                                    // 判断再上一级是否满足升级 总监
                                                                                    Customer top8Customer = customerDao.queryById(top7Customer.getParentId());
                                                                                    if(top8Customer.getLevelCopyId() <= top7Customer.getLevelCopyId()){
                                                                                        List<Customer> list8 = customerDao.queryCustomerByLevelCopyId_supreme(5, top8Customer.getId()); // 5=至尊
                                                                                        int size8 = list8.size();
                                                                                        if(size8 >= 6){
                                                                                            if(top8Customer.getLevelCopyId() >= 5 && top8Customer.getLevelCopyId() < 9){
                                                                                                top8Customer.setLevelCopyId(9); // 升级到总监

                                                                                                // 同步拼团等级
                                                                                                top8Customer.setLevelId(6);
                                                                                                if("0".equals(top8Customer.getIsActive())){
                                                                                                    // 是否购买过拼团产品
                                                                                                    List<Orders> ordersList = ordersDao.queryOrdersByUserIdIsBuyCollage(top8Customer.getId());
                                                                                                    if(ordersList.size() > 0){
                                                                                                        top8Customer.setIsActive("1"); // 激活拼团等级
                                                                                                    }
                                                                                                }
                                                                                                // TODO 直播等级 等待完善
                                                                                                // 同步直播等级
                                                                                                top8Customer.setLevelCopy1Id(6);
                                                                                                // 判断是否购买过直播产品，买过就激活
                                                                                                top8Customer.setIsActiveCopy1("0"); // 待激活直播等级

                                                                                                // 同步蜜淘等级
                                                                                                top8Customer.setLevelCopy2Id(6);
                                                                                                if("0".equals(top8Customer.getIsActiveCopy2())){
                                                                                                    // 是否购买过蜜淘产品
                                                                                                    List<GoodsOrders> ordersList = goodsOrdersDao.queryGoodsOrdersByUserIdIsBuyBeeAmoy(top8Customer.getId());
                                                                                                    if(ordersList.size() > 0){
                                                                                                        top8Customer.setIsActive("1"); // 激活蜜淘等级
                                                                                                        if(top8Customer.getAddUpUpgrade().doubleValue() < 200000){
                                                                                                            top8Customer.setAddUpUpgradeFiction(BigDecimal.valueOf(200000).subtract(top8Customer.getAddUpUpgrade()).add(top8Customer.getAddUpUpgradeFiction()));
                                                                                                        }
                                                                                                    }
                                                                                                }

                                                                                                customerDao.update(top8Customer);
                                                                                            }

                                                                                            if(top8Customer.getParentId() != null && top8Customer.getParentId() != 1198 && top8Customer.getLevelCopyId() != 11){
                                                                                                // 判断再上一级是否满足升级 总裁
                                                                                                Customer top9Customer = customerDao.queryById(top8Customer.getParentId());
                                                                                                if(top9Customer.getLevelCopyId() <= top8Customer.getLevelCopyId()){
                                                                                                    // 查看直推的人是否达到5个至尊
                                                                                                    List<Customer> list9 = customerDao.queryCustomerByLevelCopyId_supreme(5, top9Customer.getId());
                                                                                                    int size9 = list9.size();
                                                                                                    if(size9 >= 9) { // 有就直接升级
                                                                                                        if(top9Customer.getLevelCopyId() >= 5 && top9Customer.getLevelCopyId() < 10){
                                                                                                            top9Customer.setLevelCopyId(10); // 升级到总裁

                                                                                                            // 同步拼团等级
                                                                                                            top9Customer.setLevelId(6);
                                                                                                            if("0".equals(top9Customer.getIsActive())){
                                                                                                                // 是否购买过拼团产品
                                                                                                                List<Orders> ordersList = ordersDao.queryOrdersByUserIdIsBuyCollage(top9Customer.getId());
                                                                                                                if(ordersList.size() > 0){
                                                                                                                    top9Customer.setIsActive("1"); // 激活拼团等级
                                                                                                                }
                                                                                                            }
                                                                                                            // TODO 直播等级 等待完善
                                                                                                            // 同步直播等级
                                                                                                            top9Customer.setLevelCopy1Id(6);
                                                                                                            // 判断是否购买过直播产品，买过就激活
                                                                                                            top9Customer.setIsActiveCopy1("0"); // 待激活直播等级

                                                                                                            // 同步蜜淘等级
                                                                                                            top9Customer.setLevelCopy2Id(6);
                                                                                                            if("0".equals(top9Customer.getIsActiveCopy2())){
                                                                                                                // 是否购买过蜜淘产品
                                                                                                                List<GoodsOrders> ordersList = goodsOrdersDao.queryGoodsOrdersByUserIdIsBuyBeeAmoy(top9Customer.getId());
                                                                                                                if(ordersList.size() > 0){
                                                                                                                    top9Customer.setIsActive("1"); // 激活蜜淘等级
                                                                                                                    if(top9Customer.getAddUpUpgrade().doubleValue() < 200000){
                                                                                                                        top9Customer.setAddUpUpgradeFiction(BigDecimal.valueOf(200000).subtract(top9Customer.getAddUpUpgrade()).add(top9Customer.getAddUpUpgradeFiction()));
                                                                                                                    }
                                                                                                                }
                                                                                                            }

                                                                                                            customerDao.update(top9Customer);
                                                                                                        }
                                                                                                    }else{ // 没有就找人
                                                                                                        List<Customer> queryList9 = customerDao.queryCustomerByLevelCopyId1(5, top9Customer.getId()); // top9的直推,等级小于至尊的
                                                                                                        if(queryList9.size() > 0){
                                                                                                            int index9 = size9;
                                                                                                            for (Customer c9 : queryList9) {
                                                                                                                // 为top9寻找至尊 当前子级下是否存在至尊
                                                                                                                int temp = customerService.recursionCustomer(5, c9.getId());
                                                                                                                if(temp > 0){
                                                                                                                    c9.setSupreme("1");
                                                                                                                    customerDao.update(c9);
                                                                                                                }
                                                                                                                index9 += temp;
                                                                                                                if (index9 >= 9) {
                                                                                                                    if(top9Customer.getLevelCopyId() >= 5 && top9Customer.getLevelCopyId() < 10){
                                                                                                                        top9Customer.setLevelCopyId(10); // 升级到总裁

                                                                                                                        // 同步拼团等级
                                                                                                                        top9Customer.setLevelId(6);
                                                                                                                        if("0".equals(top9Customer.getIsActive())){
                                                                                                                            // 是否购买过拼团产品
                                                                                                                            List<Orders> ordersList = ordersDao.queryOrdersByUserIdIsBuyCollage(top9Customer.getId());
                                                                                                                            if(ordersList.size() > 0){
                                                                                                                                top9Customer.setIsActive("1"); // 激活拼团等级
                                                                                                                            }
                                                                                                                        }
                                                                                                                        // TODO 直播等级 等待完善
                                                                                                                        // 同步直播等级
                                                                                                                        top9Customer.setLevelCopy1Id(6);
                                                                                                                        // 判断是否购买过直播产品，买过就激活
                                                                                                                        top9Customer.setIsActiveCopy1("0"); // 待激活直播等级

                                                                                                                        // 同步蜜淘等级
                                                                                                                        top9Customer.setLevelCopy2Id(6);
                                                                                                                        if("0".equals(top9Customer.getIsActiveCopy2())){
                                                                                                                            // 是否购买过蜜淘产品
                                                                                                                            List<GoodsOrders> ordersList = goodsOrdersDao.queryGoodsOrdersByUserIdIsBuyBeeAmoy(top9Customer.getId());
                                                                                                                            if(ordersList.size() > 0){
                                                                                                                                top9Customer.setIsActive("1"); // 激活蜜淘等级
                                                                                                                                if(top9Customer.getAddUpUpgrade().doubleValue() < 200000){
                                                                                                                                    top9Customer.setAddUpUpgradeFiction(BigDecimal.valueOf(200000).subtract(top9Customer.getAddUpUpgrade()).add(top9Customer.getAddUpUpgradeFiction()));
                                                                                                                                }
                                                                                                                            }
                                                                                                                        }

                                                                                                                        customerDao.update(top9Customer);
                                                                                                                    }
                                                                                                                    break;
                                                                                                                }
                                                                                                            }
                                                                                                        }
                                                                                                    }
                                                                                                }
                                                                                            }
                                                                                        }else{
                                                                                            List<Customer> queryList8 = customerDao.queryCustomerByLevelCopyId1(5, top8Customer.getId());
                                                                                            if(queryList8.size() > 0){
                                                                                                int index8 = size8;
                                                                                                for (Customer c8 : queryList8) {
                                                                                                    int temp = customerService.recursionCustomer(5, c8.getId());
                                                                                                    if(temp > 0){
                                                                                                        c8.setSupreme("1");
                                                                                                        customerDao.update(c8);
                                                                                                    }
                                                                                                    index8 += temp;
                                                                                                    if (index8 >= 6) {
                                                                                                        if(top8Customer.getLevelCopyId() >= 5 && top8Customer.getLevelCopyId() < 9){
                                                                                                            top8Customer.setLevelCopyId(9); // 升级到总监

                                                                                                            // 同步拼团等级
                                                                                                            top8Customer.setLevelId(6);
                                                                                                            if("0".equals(top8Customer.getIsActive())){
                                                                                                                // 是否购买过拼团产品
                                                                                                                List<Orders> ordersList = ordersDao.queryOrdersByUserIdIsBuyCollage(top8Customer.getId());
                                                                                                                if(ordersList.size() > 0){
                                                                                                                    top8Customer.setIsActive("1"); // 激活拼团等级
                                                                                                                }
                                                                                                            }
                                                                                                            // TODO 直播等级 等待完善
                                                                                                            // 同步直播等级
                                                                                                            top8Customer.setLevelCopy1Id(6);
                                                                                                            // 判断是否购买过直播产品，买过就激活
                                                                                                            top8Customer.setIsActiveCopy1("0"); // 待激活直播等级

                                                                                                            // 同步蜜淘等级
                                                                                                            top8Customer.setLevelCopy2Id(6);
                                                                                                            if("0".equals(top8Customer.getIsActiveCopy2())){
                                                                                                                // 是否购买过蜜淘产品
                                                                                                                List<GoodsOrders> ordersList = goodsOrdersDao.queryGoodsOrdersByUserIdIsBuyBeeAmoy(top8Customer.getId());
                                                                                                                if(ordersList.size() > 0){
                                                                                                                    top8Customer.setIsActive("1"); // 激活蜜淘等级
                                                                                                                    if(top8Customer.getAddUpUpgrade().doubleValue() < 200000){
                                                                                                                        top8Customer.setAddUpUpgradeFiction(BigDecimal.valueOf(200000).subtract(top8Customer.getAddUpUpgrade()).add(top8Customer.getAddUpUpgradeFiction()));
                                                                                                                    }
                                                                                                                }
                                                                                                            }

                                                                                                            customerDao.update(top8Customer);
                                                                                                        }
                                                                                                        break;
                                                                                                    }
                                                                                                }
                                                                                            }
                                                                                        }
                                                                                    }
                                                                                }
                                                                            }else{
                                                                                List<Customer> queryList7 = customerDao.queryCustomerByLevelCopyId1(5, top7Customer.getId());
                                                                                if(queryList7.size() > 0){
                                                                                    int index7 = size7;
                                                                                    for (Customer c7 : queryList7) {
                                                                                        int temp = customerService.recursionCustomer(5, c7.getId());
                                                                                        if(temp > 0){
                                                                                            c7.setSupreme("1");
                                                                                            customerDao.update(c7);
                                                                                        }
                                                                                        index7 += temp;
                                                                                        if (index7 >= 3) {
                                                                                            if(top7Customer.getLevelCopyId() >= 5 && top7Customer.getLevelCopyId() < 8){
                                                                                                top7Customer.setLevelCopyId(8); // 升级到经理

                                                                                                // 同步拼团等级
                                                                                                top7Customer.setLevelId(6);
                                                                                                if("0".equals(top7Customer.getIsActive())){
                                                                                                    // 是否购买过拼团产品
                                                                                                    List<Orders> ordersList = ordersDao.queryOrdersByUserIdIsBuyCollage(top7Customer.getId());
                                                                                                    if(ordersList.size() > 0){
                                                                                                        top7Customer.setIsActive("1"); // 激活拼团等级
                                                                                                    }
                                                                                                }
                                                                                                // TODO 直播等级 等待完善
                                                                                                // 同步直播等级
                                                                                                top7Customer.setLevelCopy1Id(6);
                                                                                                // 判断是否购买过直播产品，买过就激活
                                                                                                top7Customer.setIsActiveCopy1("0"); // 待激活直播等级

                                                                                                // 同步蜜淘等级
                                                                                                top7Customer.setLevelCopy2Id(6);
                                                                                                if("0".equals(top7Customer.getIsActiveCopy2())){
                                                                                                    // 是否购买过蜜淘产品
                                                                                                    List<GoodsOrders> ordersList = goodsOrdersDao.queryGoodsOrdersByUserIdIsBuyBeeAmoy(top7Customer.getId());
                                                                                                    if(ordersList.size() > 0){
                                                                                                        top7Customer.setIsActive("1"); // 激活蜜淘等级
                                                                                                        if(top7Customer.getAddUpUpgrade().doubleValue() < 200000){
                                                                                                            top7Customer.setAddUpUpgradeFiction(BigDecimal.valueOf(200000).subtract(top7Customer.getAddUpUpgrade()).add(top7Customer.getAddUpUpgradeFiction()));
                                                                                                        }
                                                                                                    }
                                                                                                }

                                                                                                customerDao.update(top7Customer);
                                                                                            }
                                                                                            break;
                                                                                        }
                                                                                    }
                                                                                }
                                                                            }
                                                                        }
                                                                    }
                                                                }else{
                                                                    List<Customer> queryList6 = customerDao.queryCustomerByLevelCopyId1(5, top6Customer.getId());
                                                                    if(queryList6.size() > 0){
                                                                        int index6 = size6;
                                                                        for (Customer c6 : queryList6) {
                                                                            int temp = customerService.recursionCustomer(5, c6.getId());
                                                                            if(temp > 0){
                                                                                c6.setSupreme("1");
                                                                                customerDao.update(c6);
                                                                            }
                                                                            index6 += temp;
                                                                            if (index6 >= 2) {
                                                                                if(top6Customer.getLevelCopyId() >= 5 && top6Customer.getLevelCopyId() < 7){
                                                                                    top6Customer.setLevelCopyId(7); // 升级到主管

                                                                                    // 同步拼团等级
                                                                                    top6Customer.setLevelId(6);
                                                                                    if("0".equals(top6Customer.getIsActive())){
                                                                                        // 是否购买过拼团产品
                                                                                        List<Orders> ordersList = ordersDao.queryOrdersByUserIdIsBuyCollage(top6Customer.getId());
                                                                                        if(ordersList.size() > 0){
                                                                                            top6Customer.setIsActive("1"); // 激活拼团等级
                                                                                        }
                                                                                    }
                                                                                    // TODO 直播等级 等待完善
                                                                                    // 同步直播等级
                                                                                    top6Customer.setLevelCopy1Id(6);
                                                                                    // 判断是否购买过直播产品，买过就激活
                                                                                    top6Customer.setIsActiveCopy1("0"); // 待激活直播等级

                                                                                    // 同步蜜淘等级
                                                                                    top6Customer.setLevelCopy2Id(6);
                                                                                    if("0".equals(top6Customer.getIsActiveCopy2())){
                                                                                        // 是否购买过蜜淘产品
                                                                                        List<GoodsOrders> ordersList = goodsOrdersDao.queryGoodsOrdersByUserIdIsBuyBeeAmoy(top6Customer.getId());
                                                                                        if(ordersList.size() > 0){
                                                                                            top6Customer.setIsActive("1"); // 激活蜜淘等级
                                                                                            if(top6Customer.getAddUpUpgrade().doubleValue() < 200000){
                                                                                                top6Customer.setAddUpUpgradeFiction(BigDecimal.valueOf(200000).subtract(top6Customer.getAddUpUpgrade()).add(top6Customer.getAddUpUpgradeFiction()));
                                                                                            }
                                                                                        }
                                                                                    }

                                                                                    customerDao.update(top6Customer);
                                                                                }
                                                                                break;
                                                                            }
                                                                        }
                                                                    }
                                                                }
                                                            }
                                                        }
                                                    }else{
                                                        List<Customer> queryList5 = customerDao.queryCustomerByLevelCopyId1(5, top5Customer.getId());
                                                        if(queryList5.size() > 0){
                                                            int index5 = size5;
                                                            for (Customer c5 : queryList5) {
                                                                int temp = customerService.recursionCustomer(5, c5.getId());
                                                                if(temp > 0){
                                                                    c5.setSupreme("1");
                                                                    customerDao.update(c5);
                                                                }
                                                                index5 += temp;
                                                                if (index5 >= 1) {
                                                                    if(top5Customer.getLevelCopyId() >= 5 && top5Customer.getLevelCopyId() < 6){
                                                                        top5Customer.setLevelCopyId(6); // 升级到专员

                                                                        // 同步拼团等级
                                                                        top5Customer.setLevelId(6);
                                                                        if("0".equals(top5Customer.getIsActive())){
                                                                            // 是否购买过拼团产品
                                                                            List<Orders> ordersList = ordersDao.queryOrdersByUserIdIsBuyCollage(top5Customer.getId());
                                                                            if(ordersList.size() > 0){
                                                                                top5Customer.setIsActive("1"); // 激活拼团等级
                                                                            }
                                                                        }
                                                                        // TODO 直播等级 等待完善
                                                                        // 同步直播等级
                                                                        top5Customer.setLevelCopy1Id(6);
                                                                        // 判断是否购买过直播产品，买过就激活
                                                                        top5Customer.setIsActiveCopy1("0"); // 待激活直播等级

                                                                        // 同步蜜淘等级
                                                                        top5Customer.setLevelCopy2Id(6);
                                                                        if("0".equals(top5Customer.getIsActiveCopy2())){
                                                                            // 是否购买过蜜淘产品
                                                                            List<GoodsOrders> ordersList = goodsOrdersDao.queryGoodsOrdersByUserIdIsBuyBeeAmoy(top5Customer.getId());
                                                                            if(ordersList.size() > 0){
                                                                                top5Customer.setIsActive("1"); // 激活蜜淘等级
                                                                                if(top5Customer.getAddUpUpgrade().doubleValue() < 200000){
                                                                                    top5Customer.setAddUpUpgradeFiction(BigDecimal.valueOf(200000).subtract(top5Customer.getAddUpUpgrade()).add(top5Customer.getAddUpUpgradeFiction()));
                                                                                }
                                                                            }
                                                                        }

                                                                        customerDao.update(top5Customer);
                                                                    }
                                                                    break;
                                                                }
                                                            }
                                                        }
                                                    }
                                                }
                                            }
                                        }else {
                                            List<Customer> queryList4 = customerDao.queryCustomerByLevelCopyId1(4, top4Customer.getId());
                                            if(queryList4.size() > 0){
                                                int index4 = size4;
                                                for (Customer c4 : queryList4) {
                                                    int temp = customerService.recursionCustomer(4, c4.getId());
                                                    if(temp > 0){
                                                        c4.setTheKing("1");
                                                        customerDao.update(c4);
                                                    }
                                                    index4 += temp;
                                                    if (index4 >= 3) {
                                                        if(top4Customer.getLevelCopyId() > 1){
                                                            top4Customer.setLevelCopyId(5); // 升级到至尊

                                                            // 同步拼团等级
                                                            top4Customer.setLevelId(5);
                                                            if("0".equals(top4Customer.getIsActive())){
                                                                // 是否购买过拼团产品
                                                                List<Orders> ordersList = ordersDao.queryOrdersByUserIdIsBuyCollage(top4Customer.getId());
                                                                if(ordersList.size() > 0){
                                                                    top4Customer.setIsActive("1"); // 激活拼团等级
                                                                }
                                                            }
                                                            // TODO 直播等级 等待完善
                                                            // 同步直播等级
                                                            top4Customer.setLevelCopy1Id(5);
                                                            // 判断是否购买过直播产品，买过就激活
                                                            top4Customer.setIsActiveCopy1("0"); // 待激活直播等级

                                                            // 同步蜜淘等级
                                                            top4Customer.setLevelCopy2Id(5);
                                                            if("0".equals(top4Customer.getIsActiveCopy2())){
                                                                // 是否购买过蜜淘产品
                                                                List<GoodsOrders> ordersList = goodsOrdersDao.queryGoodsOrdersByUserIdIsBuyBeeAmoy(top4Customer.getId());
                                                                if(ordersList.size() > 0){
                                                                    top4Customer.setIsActive("1"); // 激活蜜淘等级
                                                                    if(top4Customer.getAddUpUpgrade().doubleValue() < 100000){
                                                                        top4Customer.setAddUpUpgradeFiction(BigDecimal.valueOf(100000).subtract(top4Customer.getAddUpUpgrade()).add(top4Customer.getAddUpUpgradeFiction()));
                                                                    }
                                                                }
                                                            }

                                                            customerDao.update(top4Customer);
                                                        }
                                                        break;
                                                    }
                                                }
                                            }
                                        }
                                    }
                                }
                            }else{
                                List<Customer> queryList3 = customerDao.queryCustomerByLevelCopyId1(3, top3Customer.getId());
                                if(queryList3.size() > 0){
                                    int index3 = size3;
                                    for (Customer c3 : queryList3) {
                                        int temp = customerService.recursionCustomer(3, c3.getId());
                                        if(temp > 0){
                                            c3.setKiller("1");
                                            customerDao.update(c3);
                                        }
                                        index3 += temp;
                                        if (index3 >= 6) {
                                            if(top3Customer.getLevelCopyId() > 1){
                                                top3Customer.setLevelCopyId(4); // 升级到王者

                                                // 同步拼团等级
                                                top3Customer.setLevelId(4);
                                                if("0".equals(top3Customer.getIsActive())){
                                                    // 是否购买过拼团产品
                                                    List<Orders> ordersList = ordersDao.queryOrdersByUserIdIsBuyCollage(top3Customer.getId());
                                                    if(ordersList.size() > 0){
                                                        top3Customer.setIsActive("1"); // 激活拼团等级
                                                    }
                                                }
                                                // TODO 直播等级 等待完善
                                                // 同步直播等级
                                                top3Customer.setLevelCopy1Id(4);
                                                // 判断是否购买过直播产品，买过就激活
                                                top3Customer.setIsActiveCopy1("0"); // 待激活直播等级

                                                // 同步蜜淘等级
                                                top3Customer.setLevelCopy2Id(4);
                                                if("0".equals(top3Customer.getIsActiveCopy2())){
                                                    // 是否购买过蜜淘产品
                                                    List<GoodsOrders> ordersList = goodsOrdersDao.queryGoodsOrdersByUserIdIsBuyBeeAmoy(top3Customer.getId());
                                                    if(ordersList.size() > 0){
                                                        top3Customer.setIsActive("1"); // 激活蜜淘等级
                                                        if(top3Customer.getAddUpUpgrade().doubleValue() < 50000){
                                                            top3Customer.setAddUpUpgradeFiction(BigDecimal.valueOf(50000).subtract(top3Customer.getAddUpUpgrade()).add(top3Customer.getAddUpUpgradeFiction()));
                                                        }
                                                    }
                                                }

                                                customerDao.update(top3Customer);
                                            }
                                            break;
                                        }
                                    }
                                }
                            }
                        }
                    }
                }

            }
            // 36900礼包
            else if(totalAmount >= 36900){

                if(customer.getLevelCopyId() < 4){
                    customer.setLevelCopyId(4); // 升级为王者
                    if("0".equals(customer.getIsActiveCopy())){
                        customer.setIsActiveCopy("1"); // 激活共享等级
                    }
                    // 同步拼团等级
                    customer.setLevelId(4);
                    if("0".equals(customer.getIsActive())){
                        // 是否购买过拼团产品
                        List<Orders> ordersList = ordersDao.queryOrdersByUserIdIsBuyCollage(customer.getId());
                        if(ordersList.size() > 0){
                            customer.setIsActive("1"); // 激活拼团等级
                        }
                    }

                    // 同步直播等级
                    customer.setLevelCopy1Id(4);
                    // 判断是否购买过直播产品，买过就激活
                    customer.setIsActiveCopy1("0"); // 待激活直播等级

                    // 同步蜜淘等级
                    customer.setLevelCopy2Id(4);
                    if("0".equals(customer.getIsActiveCopy2())){
                        // 是否购买过蜜淘产品
                        List<GoodsOrders> ordersList = goodsOrdersDao.queryGoodsOrdersByUserIdIsBuyBeeAmoy(customer.getId());
                        if(ordersList.size() > 0){
                            customer.setIsActive("1"); // 激活蜜淘等级
                        }
                    }

                    customerDao.update(customer);

                    if(customer.getParentId() != null && customer.getParentId() != 1198 && customer.getLevelCopyId() != 11){
                        // 判断再上一级是否满足升级 至尊
                        Customer top4Customer = customerDao.queryById(customer.getParentId());
                        if(top4Customer.getLevelCopyId() <= customer.getLevelCopyId()){
                            List<Customer> list4 = customerDao.queryCustomerByLevelCopyId_theKing(4, top4Customer.getId()); // 4=王者
                            int size4 = list4.size();
                            if(size4 >= 3){
                                if(top4Customer.getLevelCopyId() > 1) {
                                    top4Customer.setLevelCopyId(5); // 升级到至尊

                                    // 同步拼团等级
                                    top4Customer.setLevelId(5);
                                    if("0".equals(top4Customer.getIsActive())){
                                        // 是否购买过拼团产品
                                        List<Orders> ordersList = ordersDao.queryOrdersByUserIdIsBuyCollage(top4Customer.getId());
                                        if(ordersList.size() > 0){
                                            top4Customer.setIsActive("1"); // 激活拼团等级
                                        }
                                    }
                                    // TODO 直播等级 等待完善
                                    // 同步直播等级
                                    top4Customer.setLevelCopy1Id(5);
                                    // 判断是否购买过直播产品，买过就激活
                                    top4Customer.setIsActiveCopy1("0"); // 待激活直播等级

                                    // 同步蜜淘等级
                                    top4Customer.setLevelCopy2Id(5);
                                    if("0".equals(top4Customer.getIsActiveCopy2())){
                                        // 是否购买过蜜淘产品
                                        List<GoodsOrders> ordersList = goodsOrdersDao.queryGoodsOrdersByUserIdIsBuyBeeAmoy(top4Customer.getId());
                                        if(ordersList.size() > 0){
                                            top4Customer.setIsActive("1"); // 激活蜜淘等级
                                            if(top4Customer.getAddUpUpgrade().doubleValue() < 100000){
                                                top4Customer.setAddUpUpgradeFiction(BigDecimal.valueOf(100000).subtract(top4Customer.getAddUpUpgrade()).add(top4Customer.getAddUpUpgradeFiction()));
                                            }
                                        }
                                    }

                                    customerDao.update(top4Customer);
                                }

                                if(top4Customer.getParentId() != null && top4Customer.getParentId() != 1198 && top4Customer.getLevelCopyId() != 11){
                                    // 判断再上一级是否满足升级 专员
                                    Customer top5Customer = customerDao.queryById(top4Customer.getParentId());
                                    if(top5Customer.getLevelCopyId() <= top4Customer.getLevelCopyId()){
                                        List<Customer> list5 = customerDao.queryCustomerByLevelCopyId_supreme(5, top5Customer.getId()); // 5=至尊
                                        int size5 = list5.size();
                                        if(size5 >= 1){
                                            if(top5Customer.getLevelCopyId() == 5){
                                                top5Customer.setLevelCopyId(6); // 升级到专员

                                                // 同步拼团等级
                                                top5Customer.setLevelId(6);
                                                if("0".equals(top5Customer.getIsActive())){
                                                    // 是否购买过拼团产品
                                                    List<Orders> ordersList = ordersDao.queryOrdersByUserIdIsBuyCollage(top5Customer.getId());
                                                    if(ordersList.size() > 0){
                                                        top5Customer.setIsActive("1"); // 激活拼团等级
                                                    }
                                                }
                                                // TODO 直播等级 等待完善
                                                // 同步直播等级
                                                top5Customer.setLevelCopy1Id(6);
                                                // 判断是否购买过直播产品，买过就激活
                                                top5Customer.setIsActiveCopy1("0"); // 待激活直播等级

                                                // 同步蜜淘等级
                                                top5Customer.setLevelCopy2Id(6);
                                                if("0".equals(top5Customer.getIsActiveCopy2())){
                                                    // 是否购买过蜜淘产品
                                                    List<GoodsOrders> ordersList = goodsOrdersDao.queryGoodsOrdersByUserIdIsBuyBeeAmoy(top5Customer.getId());
                                                    if(ordersList.size() > 0){
                                                        top5Customer.setIsActive("1"); // 激活蜜淘等级
                                                        if(top5Customer.getAddUpUpgrade().doubleValue() < 200000){
                                                            top5Customer.setAddUpUpgradeFiction(BigDecimal.valueOf(200000).subtract(top5Customer.getAddUpUpgrade()).add(top5Customer.getAddUpUpgradeFiction()));
                                                        }
                                                    }
                                                }

                                                customerDao.update(top5Customer);
                                            }

                                            if(top5Customer.getParentId() != null && top5Customer.getParentId() != 1198 && top5Customer.getLevelCopyId() != 11){
                                                // 判断再上一级是否满足升级 主管
                                                Customer top6Customer = customerDao.queryById(top5Customer.getParentId());
                                                if(top6Customer.getLevelCopyId() <= top5Customer.getLevelCopyId()){
                                                    List<Customer> list6 = customerDao.queryCustomerByLevelCopyId_supreme(5, top6Customer.getId()); // 5=至尊
                                                    int size6 = list6.size();
                                                    if(size6 >= 2){
                                                        if(top6Customer.getLevelCopyId() >= 5 && top6Customer.getLevelCopyId() < 7){
                                                            top6Customer.setLevelCopyId(7); // 升级到主管

                                                            // 同步拼团等级
                                                            top6Customer.setLevelId(6);
                                                            if("0".equals(top6Customer.getIsActive())){
                                                                // 是否购买过拼团产品
                                                                List<Orders> ordersList = ordersDao.queryOrdersByUserIdIsBuyCollage(top6Customer.getId());
                                                                if(ordersList.size() > 0){
                                                                    top6Customer.setIsActive("1"); // 激活拼团等级
                                                                }
                                                            }
                                                            // TODO 直播等级 等待完善
                                                            // 同步直播等级
                                                            top6Customer.setLevelCopy1Id(6);
                                                            // 判断是否购买过直播产品，买过就激活
                                                            top6Customer.setIsActiveCopy1("0"); // 待激活直播等级

                                                            // 同步蜜淘等级
                                                            top6Customer.setLevelCopy2Id(6);
                                                            if("0".equals(top6Customer.getIsActiveCopy2())){
                                                                // 是否购买过蜜淘产品
                                                                List<GoodsOrders> ordersList = goodsOrdersDao.queryGoodsOrdersByUserIdIsBuyBeeAmoy(top6Customer.getId());
                                                                if(ordersList.size() > 0){
                                                                    top6Customer.setIsActive("1"); // 激活蜜淘等级
                                                                    if(top6Customer.getAddUpUpgrade().doubleValue() < 200000){
                                                                        top6Customer.setAddUpUpgradeFiction(BigDecimal.valueOf(200000).subtract(top6Customer.getAddUpUpgrade()).add(top6Customer.getAddUpUpgradeFiction()));
                                                                    }
                                                                }
                                                            }

                                                            customerDao.update(top6Customer);
                                                        }

                                                        if(top6Customer.getParentId() != null && top6Customer.getParentId() != 1198 && top6Customer.getLevelCopyId() != 11){
                                                            // 判断再上一级是否满足升级 经理
                                                            Customer top7Customer = customerDao.queryById(top6Customer.getParentId());
                                                            if(top7Customer.getLevelCopyId() <= top6Customer.getLevelCopyId()){
                                                                List<Customer> list7 = customerDao.queryCustomerByLevelCopyId_supreme(5, top7Customer.getId()); // 5=至尊
                                                                int size7 = list7.size();
                                                                if(size7 >= 3){
                                                                    if(top7Customer.getLevelCopyId() >= 5 && top7Customer.getLevelCopyId() < 8){
                                                                        top7Customer.setLevelCopyId(8); // 升级到经理

                                                                        // 同步拼团等级
                                                                        top7Customer.setLevelId(6);
                                                                        if("0".equals(top7Customer.getIsActive())){
                                                                            // 是否购买过拼团产品
                                                                            List<Orders> ordersList = ordersDao.queryOrdersByUserIdIsBuyCollage(top7Customer.getId());
                                                                            if(ordersList.size() > 0){
                                                                                top7Customer.setIsActive("1"); // 激活拼团等级
                                                                            }
                                                                        }
                                                                        // TODO 直播等级 等待完善
                                                                        // 同步直播等级
                                                                        top7Customer.setLevelCopy1Id(6);
                                                                        // 判断是否购买过直播产品，买过就激活
                                                                        top7Customer.setIsActiveCopy1("0"); // 待激活直播等级

                                                                        // 同步蜜淘等级
                                                                        top7Customer.setLevelCopy2Id(6);
                                                                        if("0".equals(top7Customer.getIsActiveCopy2())){
                                                                            // 是否购买过蜜淘产品
                                                                            List<GoodsOrders> ordersList = goodsOrdersDao.queryGoodsOrdersByUserIdIsBuyBeeAmoy(top7Customer.getId());
                                                                            if(ordersList.size() > 0){
                                                                                top7Customer.setIsActive("1"); // 激活蜜淘等级
                                                                                if(top7Customer.getAddUpUpgrade().doubleValue() < 200000){
                                                                                    top7Customer.setAddUpUpgradeFiction(BigDecimal.valueOf(200000).subtract(top7Customer.getAddUpUpgrade()).add(top7Customer.getAddUpUpgradeFiction()));
                                                                                }
                                                                            }
                                                                        }

                                                                        customerDao.update(top7Customer);
                                                                    }

                                                                    if(top7Customer.getParentId() != null && top7Customer.getParentId() != 1198 && top7Customer.getLevelCopyId() != 11){
                                                                        // 判断再上一级是否满足升级 总监
                                                                        Customer top8Customer = customerDao.queryById(top7Customer.getParentId());
                                                                        if(top8Customer.getLevelCopyId() <= top7Customer.getLevelCopyId()){
                                                                            List<Customer> list8 = customerDao.queryCustomerByLevelCopyId_supreme(5, top8Customer.getId()); // 5=至尊
                                                                            int size8 = list8.size();
                                                                            if(size8 >= 6){
                                                                                if(top8Customer.getLevelCopyId() >= 5 && top8Customer.getLevelCopyId() < 9){
                                                                                    top8Customer.setLevelCopyId(9); // 升级到总监

                                                                                    // 同步拼团等级
                                                                                    top8Customer.setLevelId(6);
                                                                                    if("0".equals(top8Customer.getIsActive())){
                                                                                        // 是否购买过拼团产品
                                                                                        List<Orders> ordersList = ordersDao.queryOrdersByUserIdIsBuyCollage(top8Customer.getId());
                                                                                        if(ordersList.size() > 0){
                                                                                            top8Customer.setIsActive("1"); // 激活拼团等级
                                                                                        }
                                                                                    }
                                                                                    // TODO 直播等级 等待完善
                                                                                    // 同步直播等级
                                                                                    top8Customer.setLevelCopy1Id(6);
                                                                                    // 判断是否购买过直播产品，买过就激活
                                                                                    top8Customer.setIsActiveCopy1("0"); // 待激活直播等级

                                                                                    // 同步蜜淘等级
                                                                                    top8Customer.setLevelCopy2Id(6);
                                                                                    if("0".equals(top8Customer.getIsActiveCopy2())){
                                                                                        // 是否购买过蜜淘产品
                                                                                        List<GoodsOrders> ordersList = goodsOrdersDao.queryGoodsOrdersByUserIdIsBuyBeeAmoy(top8Customer.getId());
                                                                                        if(ordersList.size() > 0){
                                                                                            top8Customer.setIsActive("1"); // 激活蜜淘等级
                                                                                            if(top8Customer.getAddUpUpgrade().doubleValue() < 200000){
                                                                                                top8Customer.setAddUpUpgradeFiction(BigDecimal.valueOf(200000).subtract(top8Customer.getAddUpUpgrade()).add(top8Customer.getAddUpUpgradeFiction()));
                                                                                            }
                                                                                        }
                                                                                    }

                                                                                    customerDao.update(top8Customer);
                                                                                }

                                                                                if(top8Customer.getParentId() != null && top8Customer.getParentId() != 1198 && top8Customer.getLevelCopyId() != 11){
                                                                                    // 判断再上一级是否满足升级 总裁
                                                                                    Customer top9Customer = customerDao.queryById(top8Customer.getParentId());
                                                                                    if(top9Customer.getLevelCopyId() <= top8Customer.getLevelCopyId()){
                                                                                        // 查看直推的人是否达到5个至尊
                                                                                        List<Customer> list9 = customerDao.queryCustomerByLevelCopyId_supreme(5, top9Customer.getId());
                                                                                        int size9 = list9.size();
                                                                                        if(size9 >= 9) { // 有就直接升级
                                                                                            if(top9Customer.getLevelCopyId() >= 5 && top9Customer.getLevelCopyId() < 10){
                                                                                                top9Customer.setLevelCopyId(10); // 升级到总裁

                                                                                                // 同步拼团等级
                                                                                                top9Customer.setLevelId(6);
                                                                                                if("0".equals(top9Customer.getIsActive())){
                                                                                                    // 是否购买过拼团产品
                                                                                                    List<Orders> ordersList = ordersDao.queryOrdersByUserIdIsBuyCollage(top9Customer.getId());
                                                                                                    if(ordersList.size() > 0){
                                                                                                        top9Customer.setIsActive("1"); // 激活拼团等级
                                                                                                    }
                                                                                                }
                                                                                                // TODO 直播等级 等待完善
                                                                                                // 同步直播等级
                                                                                                top9Customer.setLevelCopy1Id(6);
                                                                                                // 判断是否购买过直播产品，买过就激活
                                                                                                top9Customer.setIsActiveCopy1("0"); // 待激活直播等级

                                                                                                // 同步蜜淘等级
                                                                                                top9Customer.setLevelCopy2Id(6);
                                                                                                if("0".equals(top9Customer.getIsActiveCopy2())){
                                                                                                    // 是否购买过蜜淘产品
                                                                                                    List<GoodsOrders> ordersList = goodsOrdersDao.queryGoodsOrdersByUserIdIsBuyBeeAmoy(top9Customer.getId());
                                                                                                    if(ordersList.size() > 0){
                                                                                                        top9Customer.setIsActive("1"); // 激活蜜淘等级
                                                                                                        if(top9Customer.getAddUpUpgrade().doubleValue() < 200000){
                                                                                                            top9Customer.setAddUpUpgradeFiction(BigDecimal.valueOf(200000).subtract(top9Customer.getAddUpUpgrade()).add(top9Customer.getAddUpUpgradeFiction()));
                                                                                                        }
                                                                                                    }
                                                                                                }

                                                                                                customerDao.update(top9Customer);
                                                                                            }
                                                                                        }else{ // 没有就找人
                                                                                            List<Customer> queryList9 = customerDao.queryCustomerByLevelCopyId1(5, top9Customer.getId()); // top9的直推,等级小于至尊的
                                                                                            if(queryList9.size() > 0){
                                                                                                int index9 = size9;
                                                                                                for (Customer c9 : queryList9) {
                                                                                                    // 为top9寻找至尊 当前子级下是否存在至尊
                                                                                                    int temp = customerService.recursionCustomer(5, c9.getId());
                                                                                                    if(temp > 0){
                                                                                                        c9.setSupreme("1");
                                                                                                        customerDao.update(c9);
                                                                                                    }
                                                                                                    index9 += temp;
                                                                                                    if (index9 >= 9) {
                                                                                                        if(top9Customer.getLevelCopyId() >= 5 && top9Customer.getLevelCopyId() < 10){
                                                                                                            top9Customer.setLevelCopyId(10); // 升级到总裁

                                                                                                            // 同步拼团等级
                                                                                                            top9Customer.setLevelId(6);
                                                                                                            if("0".equals(top9Customer.getIsActive())){
                                                                                                                // 是否购买过拼团产品
                                                                                                                List<Orders> ordersList = ordersDao.queryOrdersByUserIdIsBuyCollage(top9Customer.getId());
                                                                                                                if(ordersList.size() > 0){
                                                                                                                    top9Customer.setIsActive("1"); // 激活拼团等级
                                                                                                                }
                                                                                                            }
                                                                                                            // TODO 直播等级 等待完善
                                                                                                            // 同步直播等级
                                                                                                            top9Customer.setLevelCopy1Id(6);
                                                                                                            // 判断是否购买过直播产品，买过就激活
                                                                                                            top9Customer.setIsActiveCopy1("0"); // 待激活直播等级

                                                                                                            // 同步蜜淘等级
                                                                                                            top9Customer.setLevelCopy2Id(6);
                                                                                                            if("0".equals(top9Customer.getIsActiveCopy2())){
                                                                                                                // 是否购买过蜜淘产品
                                                                                                                List<GoodsOrders> ordersList = goodsOrdersDao.queryGoodsOrdersByUserIdIsBuyBeeAmoy(top9Customer.getId());
                                                                                                                if(ordersList.size() > 0){
                                                                                                                    top9Customer.setIsActive("1"); // 激活蜜淘等级
                                                                                                                    if(top9Customer.getAddUpUpgrade().doubleValue() < 200000){
                                                                                                                        top9Customer.setAddUpUpgradeFiction(BigDecimal.valueOf(200000).subtract(top9Customer.getAddUpUpgrade()).add(top9Customer.getAddUpUpgradeFiction()));
                                                                                                                    }
                                                                                                                }
                                                                                                            }

                                                                                                            customerDao.update(top9Customer);
                                                                                                        }
                                                                                                        break;
                                                                                                    }
                                                                                                }
                                                                                            }
                                                                                        }
                                                                                    }
                                                                                }
                                                                            }else{
                                                                                List<Customer> queryList8 = customerDao.queryCustomerByLevelCopyId1(5, top8Customer.getId());
                                                                                if(queryList8.size() > 0){
                                                                                    int index8 = size8;
                                                                                    for (Customer c8 : queryList8) {
                                                                                        int temp = customerService.recursionCustomer(5, c8.getId());
                                                                                        if(temp > 0){
                                                                                            c8.setSupreme("1");
                                                                                            customerDao.update(c8);
                                                                                        }
                                                                                        index8 += temp;
                                                                                        if (index8 >= 6) {
                                                                                            if(top8Customer.getLevelCopyId() >= 5 && top8Customer.getLevelCopyId() < 9){
                                                                                                top8Customer.setLevelCopyId(9); // 升级到总监

                                                                                                // 同步拼团等级
                                                                                                top8Customer.setLevelId(6);
                                                                                                if("0".equals(top8Customer.getIsActive())){
                                                                                                    // 是否购买过拼团产品
                                                                                                    List<Orders> ordersList = ordersDao.queryOrdersByUserIdIsBuyCollage(top8Customer.getId());
                                                                                                    if(ordersList.size() > 0){
                                                                                                        top8Customer.setIsActive("1"); // 激活拼团等级
                                                                                                    }
                                                                                                }
                                                                                                // TODO 直播等级 等待完善
                                                                                                // 同步直播等级
                                                                                                top8Customer.setLevelCopy1Id(6);
                                                                                                // 判断是否购买过直播产品，买过就激活
                                                                                                top8Customer.setIsActiveCopy1("0"); // 待激活直播等级

                                                                                                // 同步蜜淘等级
                                                                                                top8Customer.setLevelCopy2Id(6);
                                                                                                if("0".equals(top8Customer.getIsActiveCopy2())){
                                                                                                    // 是否购买过蜜淘产品
                                                                                                    List<GoodsOrders> ordersList = goodsOrdersDao.queryGoodsOrdersByUserIdIsBuyBeeAmoy(top8Customer.getId());
                                                                                                    if(ordersList.size() > 0){
                                                                                                        top8Customer.setIsActive("1"); // 激活蜜淘等级
                                                                                                        if(top8Customer.getAddUpUpgrade().doubleValue() < 200000){
                                                                                                            top8Customer.setAddUpUpgradeFiction(BigDecimal.valueOf(200000).subtract(top8Customer.getAddUpUpgrade()).add(top8Customer.getAddUpUpgradeFiction()));
                                                                                                        }
                                                                                                    }
                                                                                                }

                                                                                                customerDao.update(top8Customer);
                                                                                            }
                                                                                            break;
                                                                                        }
                                                                                    }
                                                                                }
                                                                            }
                                                                        }
                                                                    }
                                                                }else{
                                                                    List<Customer> queryList7 = customerDao.queryCustomerByLevelCopyId1(5, top7Customer.getId());
                                                                    if(queryList7.size() > 0){
                                                                        int index7 = size7;
                                                                        for (Customer c7 : queryList7) {
                                                                            int temp = customerService.recursionCustomer(5, c7.getId());
                                                                            if(temp > 0){
                                                                                c7.setSupreme("1");
                                                                                customerDao.update(c7);
                                                                            }
                                                                            index7 += temp;
                                                                            if (index7 >= 3) {
                                                                                if(top7Customer.getLevelCopyId() >= 5 && top7Customer.getLevelCopyId() < 8){
                                                                                    top7Customer.setLevelCopyId(8); // 升级到经理

                                                                                    // 同步拼团等级
                                                                                    top7Customer.setLevelId(6);
                                                                                    if("0".equals(top7Customer.getIsActive())){
                                                                                        // 是否购买过拼团产品
                                                                                        List<Orders> ordersList = ordersDao.queryOrdersByUserIdIsBuyCollage(top7Customer.getId());
                                                                                        if(ordersList.size() > 0){
                                                                                            top7Customer.setIsActive("1"); // 激活拼团等级
                                                                                        }
                                                                                    }
                                                                                    // TODO 直播等级 等待完善
                                                                                    // 同步直播等级
                                                                                    top7Customer.setLevelCopy1Id(6);
                                                                                    // 判断是否购买过直播产品，买过就激活
                                                                                    top7Customer.setIsActiveCopy1("0"); // 待激活直播等级

                                                                                    // 同步蜜淘等级
                                                                                    top7Customer.setLevelCopy2Id(6);
                                                                                    if("0".equals(top7Customer.getIsActiveCopy2())){
                                                                                        // 是否购买过蜜淘产品
                                                                                        List<GoodsOrders> ordersList = goodsOrdersDao.queryGoodsOrdersByUserIdIsBuyBeeAmoy(top7Customer.getId());
                                                                                        if(ordersList.size() > 0){
                                                                                            top7Customer.setIsActive("1"); // 激活蜜淘等级
                                                                                            if(top7Customer.getAddUpUpgrade().doubleValue() < 200000){
                                                                                                top7Customer.setAddUpUpgradeFiction(BigDecimal.valueOf(200000).subtract(top7Customer.getAddUpUpgrade()).add(top7Customer.getAddUpUpgradeFiction()));
                                                                                            }
                                                                                        }
                                                                                    }

                                                                                    customerDao.update(top7Customer);
                                                                                }
                                                                                break;
                                                                            }
                                                                        }
                                                                    }
                                                                }
                                                            }
                                                        }
                                                    }else{
                                                        List<Customer> queryList6 = customerDao.queryCustomerByLevelCopyId1(5, top6Customer.getId());
                                                        if(queryList6.size() > 0){
                                                            int index6 = size6;
                                                            for (Customer c6 : queryList6) {
                                                                int temp = customerService.recursionCustomer(5, c6.getId());
                                                                if(temp > 0){
                                                                    c6.setSupreme("1");
                                                                    customerDao.update(c6);
                                                                }
                                                                index6 += temp;
                                                                if (index6 >= 2) {
                                                                    if(top6Customer.getLevelCopyId() >= 5 && top6Customer.getLevelCopyId() < 7){
                                                                        top6Customer.setLevelCopyId(7); // 升级到主管

                                                                        // 同步拼团等级
                                                                        top6Customer.setLevelId(6);
                                                                        if("0".equals(top6Customer.getIsActive())){
                                                                            // 是否购买过拼团产品
                                                                            List<Orders> ordersList = ordersDao.queryOrdersByUserIdIsBuyCollage(top6Customer.getId());
                                                                            if(ordersList.size() > 0){
                                                                                top6Customer.setIsActive("1"); // 激活拼团等级
                                                                            }
                                                                        }
                                                                        // TODO 直播等级 等待完善
                                                                        // 同步直播等级
                                                                        top6Customer.setLevelCopy1Id(6);
                                                                        // 判断是否购买过直播产品，买过就激活
                                                                        top6Customer.setIsActiveCopy1("0"); // 待激活直播等级

                                                                        // 同步蜜淘等级
                                                                        top6Customer.setLevelCopy2Id(6);
                                                                        if("0".equals(top6Customer.getIsActiveCopy2())){
                                                                            // 是否购买过蜜淘产品
                                                                            List<GoodsOrders> ordersList = goodsOrdersDao.queryGoodsOrdersByUserIdIsBuyBeeAmoy(top6Customer.getId());
                                                                            if(ordersList.size() > 0){
                                                                                top6Customer.setIsActive("1"); // 激活蜜淘等级
                                                                                if(top6Customer.getAddUpUpgrade().doubleValue() < 200000){
                                                                                    top6Customer.setAddUpUpgradeFiction(BigDecimal.valueOf(200000).subtract(top6Customer.getAddUpUpgrade()).add(top6Customer.getAddUpUpgradeFiction()));
                                                                                }
                                                                            }
                                                                        }

                                                                        customerDao.update(top6Customer);
                                                                    }
                                                                    break;
                                                                }
                                                            }
                                                        }
                                                    }
                                                }
                                            }
                                        }else{
                                            List<Customer> queryList5 = customerDao.queryCustomerByLevelCopyId1(5, top5Customer.getId());
                                            if(queryList5.size() > 0){
                                                int index5 = size5;
                                                for (Customer c5 : queryList5) {
                                                    int temp = customerService.recursionCustomer(5, c5.getId());
                                                    if(temp > 0){
                                                        c5.setSupreme("1");
                                                        customerDao.update(c5);
                                                    }
                                                    index5 += temp;
                                                    if (index5 >= 1) {
                                                        if(top5Customer.getLevelCopyId() >= 5 && top5Customer.getLevelCopyId() < 6){
                                                            top5Customer.setLevelCopyId(6); // 升级到专员

                                                            // 同步拼团等级
                                                            top5Customer.setLevelId(6);
                                                            if("0".equals(top5Customer.getIsActive())){
                                                                // 是否购买过拼团产品
                                                                List<Orders> ordersList = ordersDao.queryOrdersByUserIdIsBuyCollage(top5Customer.getId());
                                                                if(ordersList.size() > 0){
                                                                    top5Customer.setIsActive("1"); // 激活拼团等级
                                                                }
                                                            }
                                                            // TODO 直播等级 等待完善
                                                            // 同步直播等级
                                                            top5Customer.setLevelCopy1Id(6);
                                                            // 判断是否购买过直播产品，买过就激活
                                                            top5Customer.setIsActiveCopy1("0"); // 待激活直播等级

                                                            // 同步蜜淘等级
                                                            top5Customer.setLevelCopy2Id(6);
                                                            if("0".equals(top5Customer.getIsActiveCopy2())){
                                                                // 是否购买过蜜淘产品
                                                                List<GoodsOrders> ordersList = goodsOrdersDao.queryGoodsOrdersByUserIdIsBuyBeeAmoy(top5Customer.getId());
                                                                if(ordersList.size() > 0){
                                                                    top5Customer.setIsActive("1"); // 激活蜜淘等级
                                                                    if(top5Customer.getAddUpUpgrade().doubleValue() < 200000){
                                                                        top5Customer.setAddUpUpgradeFiction(BigDecimal.valueOf(200000).subtract(top5Customer.getAddUpUpgrade()).add(top5Customer.getAddUpUpgradeFiction()));
                                                                    }
                                                                }
                                                            }

                                                            customerDao.update(top5Customer);
                                                        }
                                                        break;
                                                    }
                                                }
                                            }
                                        }
                                    }
                                }
                            }else {
                                List<Customer> queryList4 = customerDao.queryCustomerByLevelCopyId1(4, top4Customer.getId());
                                if(queryList4.size() > 0){
                                    int index4 = size4;
                                    for (Customer c4 : queryList4) {
                                        int temp = customerService.recursionCustomer(4, c4.getId());
                                        if(temp > 0){
                                            c4.setTheKing("1");
                                            customerDao.update(c4);
                                        }
                                        index4 += temp;
                                        if (index4 >= 3) {
                                            if(top4Customer.getLevelCopyId() > 1){
                                                top4Customer.setLevelCopyId(5); // 升级到至尊

                                                // 同步拼团等级
                                                top4Customer.setLevelId(5);
                                                if("0".equals(top4Customer.getIsActive())){
                                                    // 是否购买过拼团产品
                                                    List<Orders> ordersList = ordersDao.queryOrdersByUserIdIsBuyCollage(top4Customer.getId());
                                                    if(ordersList.size() > 0){
                                                        top4Customer.setIsActive("1"); // 激活拼团等级
                                                    }
                                                }
                                                // TODO 直播等级 等待完善
                                                // 同步直播等级
                                                top4Customer.setLevelCopy1Id(5);
                                                // 判断是否购买过直播产品，买过就激活
                                                top4Customer.setIsActiveCopy1("0"); // 待激活直播等级

                                                // 同步蜜淘等级
                                                top4Customer.setLevelCopy2Id(5);
                                                if("0".equals(top4Customer.getIsActiveCopy2())){
                                                    // 是否购买过蜜淘产品
                                                    List<GoodsOrders> ordersList = goodsOrdersDao.queryGoodsOrdersByUserIdIsBuyBeeAmoy(top4Customer.getId());
                                                    if(ordersList.size() > 0){
                                                        top4Customer.setIsActive("1"); // 激活蜜淘等级
                                                        if(top4Customer.getAddUpUpgrade().doubleValue() < 100000){
                                                            top4Customer.setAddUpUpgradeFiction(BigDecimal.valueOf(100000).subtract(top4Customer.getAddUpUpgrade()).add(top4Customer.getAddUpUpgradeFiction()));
                                                        }
                                                    }
                                                }

                                                customerDao.update(top4Customer);
                                            }
                                            break;
                                        }
                                    }
                                }
                            }
                        }
                    }
                }
            }
            // 更多
            else{

            }

            // 分服务补助

            Customer cu1 = null;
            Customer cu2 = null;
            Customer cu3 = null;
            Customer cu4 = null;
            Customer cu5 = null;
            Customer cu6 = null;
            Customer cu7 = null;
            Customer cu8 = null;
            Customer cu9 = null;
            Customer cu10 = null;
            Customer cu11 = null;
            Customer cu12 = null;
            Customer cu13 = null;
            Customer cu14 = null;
            Customer cu15 = null;
            Customer cu16 = null;
            Customer cu17 = null;
            Customer cu18 = null;
            Customer cu19 = null;

            if(customer.getParentId() != null && customer.getParentId() != 1198 && customer.getLevelCopyId() != 11){
                cu1 = customerDao.queryById(customer.getParentId()); // 一层
                if (cu1 != null) {
                    if (cu1.getParentId() != null && cu1.getParentId() != 1198 && cu1.getLevelCopyId() != 11) {
                         cu2 = customerDao.queryById(cu1.getParentId()); // 二层
                        if (cu2 != null) {
                            if (cu2.getParentId() != null && cu2.getParentId() != 1198 && cu2.getLevelCopyId() != 11) {
                                 cu3 = customerDao.queryById(cu2.getParentId()); // 三层
                                if (cu3 != null) {
                                    if (cu3.getParentId() != null && cu3.getParentId() != 1198 && cu3.getLevelCopyId() != 11) {
                                         cu4 = customerDao.queryById(cu3.getParentId()); // 四层
                                        if (cu4 != null) {
                                            if (cu4.getParentId() != null && cu4.getParentId() != 1198 && cu4.getLevelCopyId() != 11) {
                                                 cu5 = customerDao.queryById(cu4.getParentId()); // 五层
                                                if (cu5 != null) {
                                                    if (cu5.getParentId() != null && cu5.getParentId() != 1198 && cu5.getLevelCopyId() != 11) {
                                                         cu6 = customerDao.queryById(cu5.getParentId()); // 六层
                                                        if (cu6 != null) {
                                                            if (cu6.getParentId() != null && cu6.getParentId() != 1198 && cu6.getLevelCopyId() != 11) {
                                                                 cu7 = customerDao.queryById(cu6.getParentId()); // 七层
                                                                if (cu7 != null) {
                                                                    if (cu7.getParentId() != null && cu7.getParentId() != 1198 && cu7.getLevelCopyId() != 11) {
                                                                         cu8 = customerDao.queryById(cu7.getParentId()); // 八层
                                                                        if (cu8 != null) {
                                                                            if (cu8.getParentId() != null && cu8.getParentId() != 1198 && cu8.getLevelCopyId() != 11) {
                                                                                 cu9 = customerDao.queryById(cu8.getParentId()); // 九层
                                                                                if (cu9 != null) {
                                                                                    if (cu9.getParentId() != null && cu9.getParentId() != 1198 && cu9.getLevelCopyId() != 11) {
                                                                                         cu10 = customerDao.queryById(cu9.getParentId()); // 十层
                                                                                        if (cu10 != null) {
                                                                                            if (cu10.getParentId() != null && cu10.getParentId() != 1198 && cu10.getLevelCopyId() != 11) {
                                                                                                 cu11 = customerDao.queryById(cu10.getParentId()); // 十一层
                                                                                                if (cu11 != null) {
                                                                                                    if (cu11.getParentId() != null && cu11.getParentId() != 1198 && cu11.getLevelCopyId() != 11) {
                                                                                                         cu12 = customerDao.queryById(cu11.getParentId()); // 十二层
                                                                                                        if (cu12 != null) {
                                                                                                            if (cu12.getParentId() != null && cu12.getParentId() != 1198 && cu12.getLevelCopyId() != 11) {
                                                                                                                 cu13 = customerDao.queryById(cu12.getParentId()); // 十三层
                                                                                                                if (cu13 != null) {
                                                                                                                    if (cu13.getParentId() != null && cu13.getParentId() != 1198 && cu13.getLevelCopyId() != 11) {
                                                                                                                         cu14 = customerDao.queryById(cu13.getParentId()); // 十四层
                                                                                                                        if (cu14 != null) {
                                                                                                                            if (cu14.getParentId() != null && cu14.getParentId() != 1198 && cu14.getLevelCopyId() != 11) {
                                                                                                                                 cu15 = customerDao.queryById(cu14.getParentId()); // 十五层
                                                                                                                                if (cu15 != null) {
                                                                                                                                    if (cu15.getParentId() != null && cu15.getParentId() != 1198 && cu15.getLevelCopyId() != 11) {
                                                                                                                                         cu16 = customerDao.queryById(cu15.getParentId()); // 十六层
                                                                                                                                        if (cu16 != null) {
                                                                                                                                            if (cu16.getParentId() != null && cu16.getParentId() != 1198 && cu16.getLevelCopyId() != 11) {
                                                                                                                                                 cu17 = customerDao.queryById(cu16.getParentId()); // 十七层
                                                                                                                                                if (cu17 != null) {
                                                                                                                                                    if (cu17.getParentId() != null && cu17.getParentId() != 1198 && cu17.getLevelCopyId() != 11) {
                                                                                                                                                         cu18 = customerDao.queryById(cu17.getParentId()); // 十八层
                                                                                                                                                        if (cu18.getParentId() != null && cu18.getParentId() != 1198 && cu18.getLevelCopyId() != 11) {
                                                                                                                                                            cu19 = customerDao.queryById(cu18.getParentId()); // 十九层

                                                                                                                                                        }
                                                                                                                                                    }
                                                                                                                                                }
                                                                                                                                            }
                                                                                                                                        }
                                                                                                                                    }
                                                                                                                                }
                                                                                                                            }
                                                                                                                        }
                                                                                                                    }
                                                                                                                }
                                                                                                            }
                                                                                                        }
                                                                                                    }
                                                                                                }
                                                                                            }
                                                                                        }
                                                                                    }
                                                                                }
                                                                            }
                                                                        }
                                                                    }
                                                                }
                                                            }
                                                        }
                                                    }
                                                }
                                            }
                                        }
                                    }
                                }
                            }
                        }
                    }
                }
            }
            // 前三级市场9元/90元/900元
            if(cu1 != null) {
                if(cu1.getLevelCopyId() >= 2 && "1".equals(cu1.getIsActiveCopy())){
                    if(totalAmount >= 369 && totalAmount < 3690){
                        BigDecimal bd9 = new BigDecimal(9);
                        handleAccount(cu1.getId(), bd9, orders.getOrderNo(), customer.getAgentCode());
                    }else if(totalAmount >= 3690 && totalAmount < 36900){
                        BigDecimal bd90 = new BigDecimal(90);
                        handleAccount(cu1.getId(), bd90, orders.getOrderNo(), customer.getAgentCode());
                    }else if(totalAmount >= 36900){
                        BigDecimal bd900 = new BigDecimal(900);
                        handleAccount(cu1.getId(), bd900, orders.getOrderNo(), customer.getAgentCode());
                    }
                }
            }
            if(cu2 != null) {
                if(cu2.getLevelCopyId() >= 2 && "1".equals(cu2.getIsActiveCopy())){
                    if(totalAmount >= 369 && totalAmount < 3690){
                        BigDecimal bd9 = new BigDecimal(9);
                        handleAccount(cu2.getId(), bd9, orders.getOrderNo(), customer.getAgentCode());
                    }else if(totalAmount >= 3690 && totalAmount < 36900){
                        BigDecimal bd90 = new BigDecimal(90);
                        handleAccount(cu2.getId(), bd90, orders.getOrderNo(), customer.getAgentCode());
                    }else if(totalAmount >= 36900){
                        BigDecimal bd900 = new BigDecimal(900);
                        handleAccount(cu2.getId(), bd900, orders.getOrderNo(), customer.getAgentCode());
                    }
                }
            }
            if(cu3 != null) {
                if(cu3.getLevelCopyId() >= 2 && "1".equals(cu3.getIsActiveCopy())){
                    if(totalAmount >= 369 && totalAmount < 3690){
                        BigDecimal bd9 = new BigDecimal(9);
                        handleAccount(cu3.getId(), bd9, orders.getOrderNo(), customer.getAgentCode());
                    }else if(totalAmount >= 3690 && totalAmount < 36900){
                        BigDecimal bd90 = new BigDecimal(90);
                        handleAccount(cu3.getId(), bd90, orders.getOrderNo(), customer.getAgentCode());
                    }else if(totalAmount >= 36900){
                        BigDecimal bd900 = new BigDecimal(900);
                        handleAccount(cu3.getId(), bd900, orders.getOrderNo(), customer.getAgentCode());
                    }
                }
            }
            // 四至六级市场6元/60元/600元
            if(cu4 != null) {
                if(cu4.getLevelCopyId() >= 3 && "1".equals(cu4.getIsActiveCopy())){
                    if(totalAmount >= 369 && totalAmount < 3690){
                        BigDecimal bd6 = new BigDecimal(6);
                        handleAccount(cu4.getId(), bd6, orders.getOrderNo(), customer.getAgentCode());
                    }else if(totalAmount >= 3690 && totalAmount < 36900){
                        BigDecimal bd60 = new BigDecimal(60);
                        handleAccount(cu4.getId(), bd60, orders.getOrderNo(), customer.getAgentCode());
                    }else if(totalAmount >= 36900){
                        BigDecimal bd600 = new BigDecimal(600);
                        handleAccount(cu4.getId(), bd600, orders.getOrderNo(), customer.getAgentCode());
                    }
                }
            }
            if(cu5 != null) {
                if(cu5.getLevelCopyId() >= 3 && "1".equals(cu5.getIsActiveCopy())){
                    if(totalAmount >= 369 && totalAmount < 3690){
                        BigDecimal bd6 = new BigDecimal(6);
                        handleAccount(cu5.getId(), bd6, orders.getOrderNo(), customer.getAgentCode());
                    }else if(totalAmount >= 3690 && totalAmount < 36900){
                        BigDecimal bd60 = new BigDecimal(60);
                        handleAccount(cu5.getId(), bd60, orders.getOrderNo(), customer.getAgentCode());
                    }else if(totalAmount >= 36900){
                        BigDecimal bd600 = new BigDecimal(600);
                        handleAccount(cu5.getId(), bd600, orders.getOrderNo(), customer.getAgentCode());
                    }
                }
            }
            if(cu6 != null) {
                if(cu6.getLevelCopyId() >= 3 && "1".equals(cu6.getIsActiveCopy())){
                    if(totalAmount >= 369 && totalAmount < 3690){
                        BigDecimal bd6 = new BigDecimal(6);
                        handleAccount(cu6.getId(), bd6, orders.getOrderNo(), customer.getAgentCode());
                    }else if(totalAmount >= 3690 && totalAmount < 36900){
                        BigDecimal bd60 = new BigDecimal(60);
                        handleAccount(cu6.getId(), bd60, orders.getOrderNo(), customer.getAgentCode());
                    }else if(totalAmount >= 36900){
                        BigDecimal bd600 = new BigDecimal(600);
                        handleAccount(cu6.getId(), bd600, orders.getOrderNo(), customer.getAgentCode());
                    }
                }
            }
            // 七至九级市场3元/30元/300元
            if(cu7 != null) {
                if(cu7.getLevelCopyId() >= 4 && "1".equals(cu7.getIsActiveCopy())){
                    if(totalAmount >= 369 && totalAmount < 3690){
                        BigDecimal bd3 = new BigDecimal(3);
                        handleAccount(cu7.getId(), bd3, orders.getOrderNo(), customer.getAgentCode());
                    }else if(totalAmount >= 3690 && totalAmount < 36900){
                        BigDecimal bd30 = new BigDecimal(30);
                        handleAccount(cu7.getId(), bd30, orders.getOrderNo(), customer.getAgentCode());
                    }else if(totalAmount >= 36900){
                        BigDecimal bd300 = new BigDecimal(300);
                        handleAccount(cu7.getId(), bd300, orders.getOrderNo(), customer.getAgentCode());
                    }
                }
            }
            if(cu8 != null) {
                if(cu8.getLevelCopyId() >= 4 && "1".equals(cu8.getIsActiveCopy())){
                    if(totalAmount >= 369 && totalAmount < 3690){
                        BigDecimal bd3 = new BigDecimal(3);
                        handleAccount(cu8.getId(), bd3, orders.getOrderNo(), customer.getAgentCode());
                    }else if(totalAmount >= 3690 && totalAmount < 36900){
                        BigDecimal bd30 = new BigDecimal(30);
                        handleAccount(cu8.getId(), bd30, orders.getOrderNo(), customer.getAgentCode());
                    }else if(totalAmount >= 36900){
                        BigDecimal bd300 = new BigDecimal(300);
                        handleAccount(cu8.getId(), bd300, orders.getOrderNo(), customer.getAgentCode());
                    }
                }
            }
            if(cu9 != null) {
                if(cu9.getLevelCopyId() >= 4 && "1".equals(cu9.getIsActiveCopy())){
                    if(totalAmount >= 369 && totalAmount < 3690){
                        BigDecimal bd3 = new BigDecimal(3);
                        handleAccount(cu9.getId(), bd3, orders.getOrderNo(), customer.getAgentCode());
                    }else if(totalAmount >= 3690 && totalAmount < 36900){
                        BigDecimal bd30 = new BigDecimal(30);
                        handleAccount(cu9.getId(), bd30, orders.getOrderNo(), customer.getAgentCode());
                    }else if(totalAmount >= 36900){
                        BigDecimal bd300 = new BigDecimal(300);
                        handleAccount(cu9.getId(), bd300, orders.getOrderNo(), customer.getAgentCode());
                    }
                }
            }
            // 十至十二级市场2元/20元/200元
            if(cu10 != null) {
                if(cu10.getLevelCopyId() >= 5 && "1".equals(cu10.getIsActiveCopy())){
                    if(totalAmount >= 369 && totalAmount < 3690){
                        BigDecimal bd2 = new BigDecimal(2);
                        handleAccount(cu10.getId(), bd2, orders.getOrderNo(), customer.getAgentCode());
                    }else if(totalAmount >= 3690 && totalAmount < 36900){
                        BigDecimal bd20 = new BigDecimal(20);
                        handleAccount(cu10.getId(), bd20, orders.getOrderNo(), customer.getAgentCode());
                    }else if(totalAmount >= 36900){
                        BigDecimal bd200 = new BigDecimal(200);
                        handleAccount(cu10.getId(), bd200, orders.getOrderNo(), customer.getAgentCode());
                    }
                }
            }
            if(cu11 != null) {
                if(cu11.getLevelCopyId() >= 5 && "1".equals(cu11.getIsActiveCopy())){
                    if(totalAmount >= 369 && totalAmount < 3690){
                        BigDecimal bd2 = new BigDecimal(2);
                        handleAccount(cu11.getId(), bd2, orders.getOrderNo(), customer.getAgentCode());
                    }else if(totalAmount >= 3690 && totalAmount < 36900){
                        BigDecimal bd20 = new BigDecimal(20);
                        handleAccount(cu11.getId(), bd20, orders.getOrderNo(), customer.getAgentCode());
                    }else if(totalAmount >= 36900){
                        BigDecimal bd200 = new BigDecimal(200);
                        handleAccount(cu11.getId(), bd200, orders.getOrderNo(), customer.getAgentCode());
                    }
                }
            }
            if(cu12 != null) {
                if(cu12.getLevelCopyId() >= 5 && "1".equals(cu12.getIsActiveCopy())){
                    if(totalAmount >= 369 && totalAmount < 3690){
                        BigDecimal bd2 = new BigDecimal(2);
                        handleAccount(cu12.getId(), bd2, orders.getOrderNo(), customer.getAgentCode());
                    }else if(totalAmount >= 3690 && totalAmount < 36900){
                        BigDecimal bd20 = new BigDecimal(20);
                        handleAccount(cu12.getId(), bd20, orders.getOrderNo(), customer.getAgentCode());
                    }else if(totalAmount >= 36900){
                        BigDecimal bd200 = new BigDecimal(200);
                        handleAccount(cu12.getId(), bd200, orders.getOrderNo(), customer.getAgentCode());
                    }
                }
            }
            // 十三至十九级市场1元/10元/100元
            if(cu13 != null) {
                if(cu13.getLevelCopyId() >= 3 && "1".equals(cu13.getIsActiveCopy())){
                    if(totalAmount >= 369 && totalAmount < 3690){
                        BigDecimal bd1 = new BigDecimal(1);
                        handleAccount(cu13.getId(), bd1, orders.getOrderNo(), customer.getAgentCode());
                    }else if(totalAmount >= 3690 && totalAmount < 36900){
                        BigDecimal bd10 = new BigDecimal(10);
                        handleAccount(cu13.getId(), bd10, orders.getOrderNo(), customer.getAgentCode());
                    }else if(totalAmount >= 36900){
                        BigDecimal bd100 = new BigDecimal(100);
                        handleAccount(cu13.getId(), bd100, orders.getOrderNo(), customer.getAgentCode());
                    }
                }
            }
            if(cu14 != null) {
                if(cu14.getLevelCopyId() >= 3 && "1".equals(cu14.getIsActiveCopy())){
                    if(totalAmount >= 369 && totalAmount < 3690){
                        BigDecimal bd1 = new BigDecimal(1);
                        handleAccount(cu14.getId(), bd1, orders.getOrderNo(), customer.getAgentCode());
                    }else if(totalAmount >= 3690 && totalAmount < 36900){
                        BigDecimal bd10 = new BigDecimal(10);
                        handleAccount(cu14.getId(), bd10, orders.getOrderNo(), customer.getAgentCode());
                    }else if(totalAmount >= 36900){
                        BigDecimal bd100 = new BigDecimal(100);
                        handleAccount(cu14.getId(), bd100, orders.getOrderNo(), customer.getAgentCode());
                    }
                }
            }
            if(cu15 != null) {
                if(cu15.getLevelCopyId() >= 3 && "1".equals(cu15.getIsActiveCopy())){
                    if(totalAmount >= 369 && totalAmount < 3690){
                        BigDecimal bd1 = new BigDecimal(1);
                        handleAccount(cu15.getId(), bd1, orders.getOrderNo(), customer.getAgentCode());
                    }else if(totalAmount >= 3690 && totalAmount < 36900){
                        BigDecimal bd10 = new BigDecimal(10);
                        handleAccount(cu15.getId(), bd10, orders.getOrderNo(), customer.getAgentCode());
                    }else if(totalAmount >= 36900){
                        BigDecimal bd100 = new BigDecimal(100);
                        handleAccount(cu15.getId(), bd100, orders.getOrderNo(), customer.getAgentCode());
                    }
                }
            }
            if(cu16 != null) {
                if(cu16.getLevelCopyId() >= 3 && "1".equals(cu16.getIsActiveCopy())){
                    if(totalAmount >= 369 && totalAmount < 3690){
                        BigDecimal bd1 = new BigDecimal(1);
                        handleAccount(cu16.getId(), bd1, orders.getOrderNo(), customer.getAgentCode());
                    }else if(totalAmount >= 3690 && totalAmount < 36900){
                        BigDecimal bd10 = new BigDecimal(10);
                        handleAccount(cu16.getId(), bd10, orders.getOrderNo(), customer.getAgentCode());
                    }else if(totalAmount >= 36900){
                        BigDecimal bd100 = new BigDecimal(100);
                        handleAccount(cu16.getId(), bd100, orders.getOrderNo(), customer.getAgentCode());
                    }
                }
            }
            if(cu17 != null) {
                if(cu17.getLevelCopyId() >= 3 && "1".equals(cu17.getIsActiveCopy())){
                    if(totalAmount >= 369 && totalAmount < 3690){
                        BigDecimal bd1 = new BigDecimal(1);
                        handleAccount(cu17.getId(), bd1, orders.getOrderNo(), customer.getAgentCode());
                    }else if(totalAmount >= 3690 && totalAmount < 36900){
                        BigDecimal bd10 = new BigDecimal(10);
                        handleAccount(cu17.getId(), bd10, orders.getOrderNo(), customer.getAgentCode());
                    }else if(totalAmount >= 36900){
                        BigDecimal bd100 = new BigDecimal(100);
                        handleAccount(cu17.getId(), bd100, orders.getOrderNo(), customer.getAgentCode());
                    }
                }
            }
            if(cu18 != null) {
                if(cu18.getLevelCopyId() >= 3 && "1".equals(cu18.getIsActiveCopy())){
                    if(totalAmount >= 369 && totalAmount < 3690){
                        BigDecimal bd1 = new BigDecimal(1);
                        handleAccount(cu18.getId(), bd1, orders.getOrderNo(), customer.getAgentCode());
                    }else if(totalAmount >= 3690 && totalAmount < 36900){
                        BigDecimal bd10 = new BigDecimal(10);
                        handleAccount(cu18.getId(), bd10, orders.getOrderNo(), customer.getAgentCode());
                    }else if(totalAmount >= 36900){
                        BigDecimal bd100 = new BigDecimal(100);
                        handleAccount(cu18.getId(), bd100, orders.getOrderNo(), customer.getAgentCode());
                    }
                }
            }
            if(cu19 != null) {
                if(cu19.getLevelCopyId() >= 3 && "1".equals(cu19.getIsActiveCopy())){
                    if(totalAmount >= 369 && totalAmount < 3690){
                        BigDecimal bd1 = new BigDecimal(1);
                        handleAccount(cu19.getId(), bd1, orders.getOrderNo(), customer.getAgentCode());
                    }else if(totalAmount >= 3690 && totalAmount < 36900){
                        BigDecimal bd10 = new BigDecimal(10);
                        handleAccount(cu19.getId(), bd10, orders.getOrderNo(), customer.getAgentCode());
                    }else if(totalAmount >= 36900){
                        BigDecimal bd100 = new BigDecimal(100);
                        handleAccount(cu19.getId(), bd100, orders.getOrderNo(), customer.getAgentCode());
                    }
                }
            }

            // 培训津贴 按实际支付金额来分配
            handleTrainingAllowances(customer, orders.getPayAmount(), orders.getOrderNo());

        }catch (Exception e){
            e.printStackTrace();

        }finally {

        }
    }


    /**
     * 处理培训津贴
     */
    public void handleTrainingAllowances(Customer customer, BigDecimal payAmount, String orderNo){
        BigDecimal bd003 = payAmount.multiply(BigDecimal.valueOf(0.03)).setScale(2, BigDecimal.ROUND_UP);
        BigDecimal bd006 = payAmount.multiply(BigDecimal.valueOf(0.06)).setScale(2, BigDecimal.ROUND_UP);
        BigDecimal bd009 = payAmount.multiply(BigDecimal.valueOf(0.09)).setScale(2, BigDecimal.ROUND_UP);
        BigDecimal bd012 = payAmount.multiply(BigDecimal.valueOf(0.12)).setScale(2, BigDecimal.ROUND_UP);

        Customer c = findParentUser_LC(customer, 2);
        if(c != null){
            if(c.getLevelCopyId() == 3 && "1".equals(c.getIsActiveCopy())){
                handleAccount1(c.getId(), bd003, orderNo, customer.getAgentCode());

                Customer c1 = findParentUser_LC(c, 3); // 获取等级高于高手的
                if(c1 != null){
                    if(c1.getLevelCopyId() == 4 && "1".equals(c1.getIsActiveCopy())){
                        handleAccount1(c1.getId(), bd003, orderNo, customer.getAgentCode());

                        Customer c2 = findParentUser_LC(c1, 4); // 获取等级高于王者的
                        if(c2 != null){
                            if(c2.getLevelCopyId() == 5 && "1".equals(c2.getIsActiveCopy())){
                                handleAccount1(c2.getId(), bd003, orderNo, customer.getAgentCode());

                                Customer c3 = findParentUser_LC(c2, 5); // 获取等级高于至尊的
                                if(c3 != null){
                                    if(c3.getLevelCopyId() >= 6 && "1".equals(c3.getIsActiveCopy())){
                                        handleAccount1(c3.getId(), bd003, orderNo, customer.getAgentCode());
                                    }
                                }

                            }else if(c2.getLevelCopyId() >= 6 && "1".equals(c2.getIsActiveCopy())){
                                handleAccount1(c2.getId(), bd006, orderNo, customer.getAgentCode());
                            }
                        }

                    }else if(c1.getLevelCopyId() == 5 && "1".equals(c1.getIsActiveCopy())){
                        handleAccount1(c1.getId(), bd006, orderNo, customer.getAgentCode());

                        Customer c2 = findParentUser_LC(c1, 5); // 获取等级高于至尊的
                        if(c2 != null){
                            if(c2.getLevelCopyId() >= 6 && "1".equals(c2.getIsActiveCopy())){
                                handleAccount1(c2.getId(), bd003, orderNo, customer.getAgentCode());
                            }
                        }

                    }else if(c1.getLevelCopyId() >= 6 && "1".equals(c1.getIsActiveCopy())){
                        handleAccount1(c1.getId(), bd009, orderNo, customer.getAgentCode());
                    }
                }

            }else if(c.getLevelCopyId() == 4 && "1".equals(c.getIsActiveCopy())){
                handleAccount1(c.getId(), bd006, orderNo, customer.getAgentCode());

                Customer c1 = findParentUser_LC(c, 4); // 获取等级高于王者的
                if(c1 != null){
                    if(c1.getLevelCopyId() == 5 && "1".equals(c1.getIsActiveCopy())){
                        handleAccount1(c1.getId(), bd003, orderNo, customer.getAgentCode());

                        Customer c2 = findParentUser_LC(c1, 5); // 获取等级高于至尊的
                        if(c2 != null){
                            if(c2.getLevelCopyId() >= 6 && "1".equals(c2.getIsActiveCopy())){
                                handleAccount1(c2.getId(), bd003, orderNo, customer.getAgentCode());
                            }
                        }

                    }else if(c1.getLevelCopyId() >= 6 && "1".equals(c1.getIsActiveCopy())){
                        handleAccount1(c1.getId(), bd006, orderNo, customer.getAgentCode());
                    }
                }

            }else if(c.getLevelCopyId() == 5 && "1".equals(c.getIsActiveCopy())){
                handleAccount1(c.getId(), bd009, orderNo, customer.getAgentCode());

                Customer c1 = findParentUser_LC(c, 5); // 获取等级高于至尊的
                if(c1 != null){
                    if(c1.getLevelCopyId() > 5 && "1".equals(c1.getIsActiveCopy())){
                        handleAccount1(c1.getId(), bd003, orderNo, customer.getAgentCode());
                    }
                }

            }else if(c.getLevelCopyId() >= 6 && "1".equals(c.getIsActiveCopy())){
                handleAccount1(c.getId(), bd012, orderNo, customer.getAgentCode());
            }
        }

    }


    /**
     * 获取就近高等级 - 分配培训津贴
     * @param customer
     * @param levelCopyId
     * @return
     */
    public Customer findParentUser_LC(Customer customer, Integer levelCopyId){
        Integer newId = 0;
        if (customer.getParentId() != null && customer.getParentId() != 1198 && customer.getLevelCopyId() != 11) {
            newId = customer.getParentId();
        }
        Customer newCustomer = customerDao.queryById(newId);
        if(newCustomer == null){
            return newCustomer;
        }
        if (newCustomer.getLevelCopyId() > levelCopyId) {
            return newCustomer;
        } else {
            while (newCustomer.getLevelCopyId() <= levelCopyId) {
                newCustomer = customerDao.queryById(newId);
                if(newCustomer == null){
                    break;
                }
                if (newCustomer.getLevelCopyId() > levelCopyId) {
                    break;
                } else {
                    if (newCustomer.getParentId() != null && newCustomer.getParentId() != 1198 && newCustomer.getLevelCopyId() != 11) {
                        newId = newCustomer.getParentId();
                    }else{
                        break;
                    }
                }
            }
        }
        return newCustomer;
    }


    /**
     * 共享模式 - 服务补助
     * @param userId
     * @param bd
     * @param orderNo
     * @param agentCode
     */
    public void handleAccount(Integer userId, BigDecimal bd, String orderNo, String agentCode){
        Account acc1 = accountDao.queryAccountByUserId(userId);
        acc1.setVoucherBalance(acc1.getVoucherBalance().add(bd));
        accountDao.update(acc1);
        AccountRecord ar1 = new AccountRecord();
        ar1.setIntoUserId(userId);
        //ar1.setOutUserId();
        ar1.setUpdateTime(new Date());
        ar1.setType("0");
        ar1.setAmount(bd);
        ar1.setNowAmount(acc1.getVoucherBalance());
        ar1.setSign("1");
        ar1.setOrderNo(orderNo);
        ar1.setInfo(agentCode + "购买成功! 您获得贡献红包：" + bd);
        accountRecordDao.save(ar1);
    }


    /**
     * 共享模式 - 培训津贴
     * @param userId
     * @param bd
     * @param orderNo
     * @param agentCode
     */
    public void handleAccount1(Integer userId, BigDecimal bd, String orderNo, String agentCode){
        Account acc1 = accountDao.queryAccountByUserId(userId);
        acc1.setVoucherBalance(acc1.getVoucherBalance().add(bd));
        accountDao.update(acc1);
        AccountRecord ar1 = new AccountRecord();
        ar1.setIntoUserId(userId);
        //ar1.setOutUserId();
        ar1.setUpdateTime(new Date());
        ar1.setType("0");
        ar1.setAmount(bd);
        ar1.setNowAmount(acc1.getVoucherBalance());
        ar1.setSign("1");
        ar1.setOrderNo(orderNo);
        ar1.setInfo(agentCode + "购买成功! 您获得销售提成：" + bd);
        accountRecordDao.save(ar1);
    }


    /**
     * 共享模式 - 增加业绩
     * @param userId
     * @param bd
     * @param orderNo
     * @param agentCode
     */
    public void handleAccount2(Integer userId, BigDecimal amount, BigDecimal bd, String orderNo, String agentCode){
        AccountRecord ar1 = new AccountRecord();
        ar1.setIntoUserId(userId);
        //ar1.setOutUserId();
        ar1.setUpdateTime(new Date());
        ar1.setType("4");
        ar1.setAmount(amount);
        ar1.setNowAmount(bd);
        ar1.setSign("1");
        ar1.setOrderNo(orderNo);
        ar1.setInfo(agentCode + "购买成功! 您的业绩增加：" + amount);
        accountRecordDao.save(ar1);
    }


    /**
     * 获取七牛云token
     * @return
     */
    @GetMapping("/dmz/qiniu/token.json")
    public ResponseServer getQiNiuToken() {
        String qiNiuToken = QiNiuConst.getToken();
        return ResponseServer.success(qiNiuToken);
    }


    /**
     * 提交实名认证数据
     * @param realNameAuthDTO
     * @return
     */
    @PostMapping("/submitRealNameAuth")
    public ResponseServer submitRealNameAuth(RealNameAuthDTO realNameAuthDTO){
        Customer customer = customerDao.queryById(realNameAuthDTO.getUserId());
//        Customer customer1 = customerDao.queryCustomerByMobile(realNameAuthDTO.getUserTel());
//        if(customer1 != null){
//            if(!customer1.getId().equals(customer.getId())){
//                return ResponseServer.error("手机号码已存在!");
//            }
//        }
        customer.setRealName(realNameAuthDTO.getUserName());
        customer.setIdCard(realNameAuthDTO.getIdCard());
        //customer.setMobile(realNameAuthDTO.getUserTel());
        customer.setCardPositive(realNameAuthDTO.getCardPositive());
        customer.setCardBack(realNameAuthDTO.getCardBack());
        customer.setVerifyStatus("0");
        if(!"".equals(customer.getFailedInfo())){
            customer.setFailedInfo("");
        }
        customerDao.update(customer);
        return ResponseServer.success();
    }


    /**
     * 购买礼包，余额支付
     * @param productId
     * @param openId
     * @param consigneeName
     * @param fullAddress
     * @param consigneePhone
     * @param userId
     * @param freight
     * @return
     */
    @PostMapping("/share/pay/voucher")
    public ResponseServer sharePayVoucher(@RequestParam(required = false) Integer productId,
                                   @RequestParam(required = false) String openId,
                                   @RequestParam(required = false) String consigneeName,
                                   @RequestParam(required = false) String fullAddress,
                                   @RequestParam(required = false) String consigneePhone,
                                   @RequestParam(required = false) Integer userId,
                                   @RequestParam(required = false) BigDecimal freight,
                                          @RequestParam(required = false) BigDecimal couponPrice,
                                          @RequestParam(required = false) Integer couponQuantity,
                                          @RequestParam(required = false) Integer couponId){

        System.err.println("-------------创建订单传递的参数：productId= " + productId);
        System.err.println("-------------创建订单传递的参数：openId= " + openId);
        System.err.println("-------------创建订单传递的参数：consigneeName= " + consigneeName);
        System.err.println("-------------创建订单传递的参数：fullAddress= " + fullAddress);
        System.err.println("-------------创建订单传递的参数：consigneePhone= " + consigneePhone);
        System.err.println("-------------创建订单传递的参数：userId= " + userId);
        System.err.println("-------------创建订单传递的参数：freight= " + freight);
        System.err.println("-------------创建订单传递的参数：couponPrice= " + couponPrice);
        System.err.println("-------------创建订单传递的参数：couponQuantity= " + couponQuantity);

        Product product = productDao.queryById(productId);
        if(product == null){
            return ResponseServer.error("支付失败,产品信息错误");
        }
        Customer customer = customerDao.queryById(userId);
        if(customer == null){
            return ResponseServer.error("支付失败,用户信息不正确，请重新授权");
        }

        BigDecimal totalPrice; // 实际支付的钱
        // 商户订单号
        String outTradeNo = "BEE" + Units.getOrderIdByTime().replaceAll("-", "");
        // 交易号
        String tradeNo = "JYH" + Units.getOrderIdByTime().replaceAll("-", "");
        if (freight == null) {
            freight = BigDecimal.valueOf(0.0);
        }
        if (couponPrice == null) {
            couponPrice = BigDecimal.valueOf(0.0);
        }
        List<SkuRelation> skuList = skuRelationDao.queryByProductId(productId);
        SkuRelation sku = skuList.get(0);
        BigDecimal totalAmount = sku.getRetailPrice(); // 产品总金额
        totalPrice = sku.getRetailPrice().add(freight).subtract(couponPrice);
        Account account = accountDao.queryAccountByUserId(userId);
        if(account.getVoucherBalance().doubleValue() < totalPrice.doubleValue()){
            return ResponseServer.error("支付失败,余额不足");
        }
        account.setVoucherBalance(account.getVoucherBalance().subtract(totalPrice));
        int give = (int)Math.round(totalPrice.doubleValue());
        account.setIntegral(account.getIntegral() + give);
        accountDao.update(account);

        AccountRecord ar = new AccountRecord();
        //ar1.setIntoUserId();
        ar.setOutUserId(userId);
        ar.setUpdateTime(new Date());
        ar.setType("0");
        ar.setAmount(totalPrice);
        ar.setNowAmount(account.getVoucherBalance());
        ar.setSign("2");
        ar.setOrderNo(outTradeNo);
        ar.setInfo(customer.getAgentCode() + "购买成功! 消费余额：" + totalPrice);
        accountRecordDao.save(ar);

        AccountRecord ar1 = new AccountRecord();
        ar1.setIntoUserId(customer.getId());
        ar1.setUpdateTime(new Date());
        ar1.setType("1");
        ar1.setAmount(BigDecimal.valueOf(give));
        ar1.setNowAmount(BigDecimal.valueOf(account.getIntegral()));
        ar1.setSign("1");
        ar1.setOrderNo(outTradeNo);
        ar1.setInfo(customerDao.queryById(userId).getAgentCode() + "购买成功! 您获得积分：" + give);
        accountRecordDao.save(ar1);

        // 创建订单
        Orders orders = new Orders();
        orders.setOrderNo(outTradeNo);
        orders.setTradeNo(tradeNo);
        orders.setTotalAmount(totalAmount); // 总金额
        orders.setPayAmount(totalPrice);  // 实际支付金额
        orders.setCouponAmount(couponPrice);  // 优惠券抵扣金额
        orders.setFreight(freight); // 运费金额
        orders.setPayStatus("1");
        orders.setPayType("1");
        orders.setDealStatus("1");
        orders.setRefundStatus("0");
        orders.setPrepayId("");
        orders.setOrderPersonId(userId);
        orders.setConsigneeName(consigneeName);
        orders.setConsigneePhone(consigneePhone);
        orders.setAddress(fullAddress);
        orders.setUpdateTime(new Date());
        orders.setIsDel("0");
        orders.setIsRun("0");
        orders.setLastCollage("0");
        orders.setRemarks("无");
        orders.setProductId(product.getId());
        ordersDao.save(orders);

        OrderDetails od = new OrderDetails();
        od.setOrderNo(orders.getOrderNo());
        od.setTradeNo(orders.getTradeNo());
        od.setStoreShopId(product.getStoreShopId());
        od.setStoreShopName(storeShopDao.queryById(product.getStoreShopId()).getName());
        od.setClassifyId(product.getClassifyId());
        od.setClassifyName(classifyDao.queryById(product.getClassifyId()).getName());
        od.setProductId(product.getId());
        od.setProductType(product.getType()); // 礼包
        od.setProductImg(product.getImg());
        od.setProductName(product.getName());
        od.setProductCode(product.getProductCode());
        od.setCostPrice(sku.getCostPrice());
//                List<SkuRelation> skuList = skuRelationDao.queryByProductId(product.getId());
//                SkuRelation sku = skuList.get(0);
        od.setRelationId(sku.getId());
        if(sku.getGroupRelation().contains(",")){
            String[] strings = sku.getGroupRelation().split(",");
            String str = "";
            for(int u = 0; u < strings.length; u++){
                str += specAttributeDao.queryById(Integer.parseInt(strings[u])).getAttributeName() + "，";
            }
            od.setSpecAttributeName(str.substring(0, str.length()-1));
        }else{
            od.setSpecAttributeName(specAttributeDao.queryById(Integer.parseInt(sku.getGroupRelation())).getAttributeName());
        }
        od.setQuantity(1);
        od.setUnitPrice(sku.getRetailPrice());
        od.setUpdateTime(new Date());
        orderDetailsDao.save(od);

        // 添加销量
        product.setSales(product.getSales() + 1);
        productDao.update(product);

        // 如果使用了优惠券就扣除
        int uu = (int) (couponPrice.doubleValue() / 99);
        if(uu > 0){
            UserCoupon userCoupon = userCouponDao.queryByUserIdAndCouponId(userId, couponId);
            userCoupon.setQuantity(userCoupon.getQuantity() - uu);
            userCouponDao.update(userCoupon);

            AccountRecord accRe = new AccountRecord();
            accRe.setOutUserId(userId);
            accRe.setUpdateTime(new Date());
            accRe.setType("6");
            accRe.setAmount(BigDecimal.valueOf(uu));
            accRe.setNowAmount(BigDecimal.valueOf(userCoupon.getQuantity()));
            accRe.setSign("2");
            accRe.setOrderNo(orders.getOrderNo());
            accRe.setInfo(customerDao.queryById(userId).getAgentCode() + "购买成功! 消费共享券：" + uu);
            accountRecordDao.save(accRe);
        }


        //TODO 发送购买成功通知
//        TemplateDTO template =new TemplateDTO();
//        template.setToUser(customer.getOpenId());
//        template.setTemplateId("-2HrS0q9IBkHd-ZYDUH2MUFa_T9ONM2GWfskswEc3XE");
//        template.setPage("/pages/home/home");
//        // 封装内容
//        Map<String, Object> keyword1 = new HashMap<>();
//        keyword1.put("value", orders.getOrderNo());
//        Map<String, Object> keyword2 = new HashMap<>();
//        keyword2.put("value", orders.getPayAmount() + "元");
//        Map<String, Object> keyword3 = new HashMap<>();
//        keyword3.put("value", "请您注意查收订单物流信息");
//        // 对应小程序的模板key值
//        Map<String, Object> data = new HashMap<>();
//        data.put("character_string1", keyword1);
//        data.put("amount4", keyword2);
//        data.put("thing6", keyword3);
//        template.setContentMap(data);
//        NoticeTemplate nt =new NoticeTemplate();
//        String code = nt.sendMassage(template);
//        System.err.println("code= " + code);
//        if("0".equals(code)){
//            System.err.println("发送通知成功!!!");
//        }else{
//            System.err.println("发送通知失败!!!");
//        }


        // 调用共享模式，处理业务
        sharingMode(orders);
        addAchievement(orders);

        return ResponseServer.success("余额支付成功!!!");
    }


    /**
     * 购买中秋活动产品，余额支付
     * @param productId
     * @param openId
     * @param consigneeName
     * @param fullAddress
     * @param consigneePhone
     * @param userId
     * @param freight
     * @return
     */
    @PostMapping("/autumn/pay/voucher")
    public ResponseServer autumnPayVoucher(@RequestParam(required = false) Integer productId,
                                          @RequestParam(required = false) String openId,
                                          @RequestParam(required = false) String consigneeName,
                                          @RequestParam(required = false) String fullAddress,
                                          @RequestParam(required = false) String consigneePhone,
                                          @RequestParam(required = false) Integer userId,
                                          @RequestParam(required = false) BigDecimal freight){

        System.err.println("-------------创建订单传递的参数：productId= " + productId);
        System.err.println("-------------创建订单传递的参数：openId= " + openId);
        System.err.println("-------------创建订单传递的参数：consigneeName= " + consigneeName);
        System.err.println("-------------创建订单传递的参数：fullAddress= " + fullAddress);
        System.err.println("-------------创建订单传递的参数：consigneePhone= " + consigneePhone);
        System.err.println("-------------创建订单传递的参数：userId= " + userId);
        System.err.println("-------------创建订单传递的参数：freight= " + freight);

        Product product = productDao.queryById(productId);
        if(product == null){
            return ResponseServer.error("支付失败,产品信息错误");
        }
        Customer customer = customerDao.queryById(userId);
        if(customer == null){
            return ResponseServer.error("支付失败,用户信息不正确，请重新授权");
        }

        BigDecimal totalPrice; // 实际支付的钱
        // 商户订单号
        String outTradeNo = "BEE" + Units.getOrderIdByTime().replaceAll("-", "");
        // 交易号
        String tradeNo = "JYH" + Units.getOrderIdByTime().replaceAll("-", "");
        if (freight == null) {
            freight = BigDecimal.valueOf(0.0);
        }
        List<SkuRelation> skuList = skuRelationDao.queryByProductId(productId);
        SkuRelation sku = skuList.get(0);
        BigDecimal totalAmount = sku.getRetailPrice(); // 产品总金额
        totalPrice = sku.getRetailPrice().add(freight);
        Account account = accountDao.queryAccountByUserId(userId);
        if(account.getVoucherBalance().doubleValue() < totalPrice.doubleValue()){
            return ResponseServer.error("支付失败,余额不足");
        }
        account.setVoucherBalance(account.getVoucherBalance().subtract(totalPrice));
        int give = (int)Math.round(totalPrice.doubleValue());
        account.setIntegral(account.getIntegral() + give);
        accountDao.update(account);

        AccountRecord ar = new AccountRecord();
        ar.setOutUserId(userId);
        ar.setUpdateTime(new Date());
        ar.setType("0");
        ar.setAmount(totalPrice);
        ar.setNowAmount(account.getVoucherBalance());
        ar.setSign("2");
        ar.setOrderNo(outTradeNo);
        ar.setInfo(customer.getAgentCode() + "购买成功! 消费余额：" + totalPrice);
        accountRecordDao.save(ar);

        AccountRecord ar1 = new AccountRecord();
        ar1.setIntoUserId(customer.getId());
        ar1.setUpdateTime(new Date());
        ar1.setType("1");
        ar1.setAmount(BigDecimal.valueOf(give));
        ar1.setNowAmount(BigDecimal.valueOf(account.getIntegral()));
        ar1.setSign("1");
        ar1.setOrderNo(outTradeNo);
        ar1.setInfo(customerDao.queryById(userId).getAgentCode() + "购买成功! 您获得积分：" + give);
        accountRecordDao.save(ar1);

        // 创建订单
        Orders orders = new Orders();
        orders.setOrderNo(outTradeNo);
        orders.setTradeNo(tradeNo);
        orders.setTotalAmount(totalAmount); // 总金额
        orders.setPayAmount(totalPrice);  // 实际支付金额
        orders.setCouponAmount(new BigDecimal(0));  // 优惠券抵扣金额
        orders.setFreight(freight); // 运费金额
        orders.setPayStatus("1");
        orders.setPayType("1");
        orders.setDealStatus("1");
        orders.setRefundStatus("0");
        orders.setOrderPersonId(userId);
        orders.setConsigneeName(consigneeName);
        orders.setConsigneePhone(consigneePhone);
        orders.setAddress(fullAddress);
        orders.setUpdateTime(new Date());
        orders.setIsDel("0");
        orders.setIsRun("0");
        orders.setRemarks("中秋订单");
        orders.setProductId(product.getId());
        ordersDao.save(orders);

        OrderDetails od = new OrderDetails();
        od.setOrderNo(orders.getOrderNo());
        od.setTradeNo(orders.getTradeNo());
        od.setStoreShopId(product.getStoreShopId());
        od.setStoreShopName(storeShopDao.queryById(product.getStoreShopId()).getName());
        od.setClassifyId(product.getClassifyId());
        od.setClassifyName(classifyDao.queryById(product.getClassifyId()).getName());
        od.setProductId(product.getId());
        od.setProductType(product.getType());
        od.setProductImg(product.getImg());
        od.setProductName(product.getName());
        od.setProductCode(product.getProductCode());
        od.setCostPrice(sku.getCostPrice());
        od.setRelationId(sku.getId());
        if(sku.getGroupRelation().contains(",")){
            String[] strings = sku.getGroupRelation().split(",");
            String str = "";
            for(int u = 0; u < strings.length; u++){
                str += specAttributeDao.queryById(Integer.parseInt(strings[u])).getAttributeName() + "，";
            }
            od.setSpecAttributeName(str.substring(0, str.length()-1));
        }else{
            od.setSpecAttributeName(specAttributeDao.queryById(Integer.parseInt(sku.getGroupRelation())).getAttributeName());
        }
        od.setQuantity(1);
        od.setUnitPrice(sku.getRetailPrice());
        od.setUpdateTime(new Date());
        orderDetailsDao.save(od);

        // 添加销量
        product.setSales(product.getSales() + 1);
        productDao.update(product);

        return ResponseServer.success("余额支付成功!!!");
    }


    /**
     * 获取我的红包数据
     * @param userId
     * @return
     */
    @GetMapping("/getMyRedPackData")
    public ResponseServer getMyRedPackData(Integer userId){
        Map map = new HashMap();
        List<OpenRedPack> openRedPackList = openRedPackDao.queryByStatus(userId);
//        if(openRedPackList.size() > 0){
//            for(OpenRedPack orp : openRedPackList){
//                orp.setSign("gx");
//                openRedPackDao.update(orp);
//            }
//        }
        map.put("succ", openRedPackList);
        List<FailRedPack> failRedPackList = failRedPackDao.queryByUserId(userId);
        map.put("fail", failRedPackList);
        return ResponseServer.success("加载成功", map);
    }


    /**
     * 添加红包金额及记录
     * @param redPackId
     * @return
     */
    @GetMapping("/saveRedPack")
    public ResponseServer saveRedPack(Integer redPackId, String sign){
        BigDecimal bd = new BigDecimal(0);
        if("gx".equals(sign)){
            // 共享
            OpenRedPack openRedPack = openRedPackDao.queryById(redPackId);
            if(openRedPack != null){
                if("2".equals(openRedPack.getStatus())){
                    Account account = accountDao.queryAccountByUserId(openRedPack.getUserId());
                    account.setVoucherBalance(account.getVoucherBalance().add(openRedPack.getPrizeMoney()));
                    accountDao.update(account);
                    AccountRecord ar1 = new AccountRecord();
                    ar1.setIntoUserId(openRedPack.getUserId());
                    //ar1.setOutUserId();
                    ar1.setUpdateTime(new Date());
                    ar1.setType("0");
                    ar1.setAmount(openRedPack.getPrizeMoney());
                    ar1.setNowAmount(account.getVoucherBalance());
                    ar1.setSign("1");
                    //ar1.setOrderNo();
                    ar1.setInfo(customerDao.queryById(openRedPack.getUserId()).getAgentCode() + "开共享红包! 获得余额：" + openRedPack.getPrizeMoney());
                    accountRecordDao.save(ar1);
                    openRedPack.setStatus("1");
                    openRedPackDao.update(openRedPack);
                    bd = openRedPack.getPrizeMoney();
                }
            }
        }else{
            // 拼团
            if("pt".equals(sign)){
                FailRedPack failRedPack = failRedPackDao.queryById(redPackId);
                if(failRedPack != null){
                    if("2".equals(failRedPack.getStatus())){
                        Account account = accountDao.queryAccountByUserId(failRedPack.getUserId());
                        account.setVoucherBalance(account.getVoucherBalance().add(failRedPack.getPrizeMoney()));
                        accountDao.update(account);
                        failRedPack.setStatus("1");
                        failRedPackDao.update(failRedPack);
                        bd = failRedPack.getPrizeMoney();
                        if("0".equals(failRedPack.getMode())){
                            AccountRecord ar1 = new AccountRecord();
                            ar1.setIntoUserId(failRedPack.getUserId());
                            ar1.setUpdateTime(new Date());
                            ar1.setType("0");
                            ar1.setAmount(failRedPack.getPrizeMoney());
                            ar1.setNowAmount(account.getVoucherBalance());
                            ar1.setSign("1");
                            ar1.setOrderNo(failRedPack.getOrderNo());
                            ar1.setInfo(customerDao.queryById(failRedPack.getUserId()).getAgentCode() + "开拼团红包! 获得余额：" + failRedPack.getPrizeMoney());
                            accountRecordDao.save(ar1);
                            // 处理参与拼团后的利润分配
                            ordersCopyService.handleCollageProfit(failRedPack.getUserId(), failRedPack.getPrizeMoney(), failRedPack.getOrderNo());
                        }else{
                            AccountRecord ar1 = new AccountRecord();
                            ar1.setIntoUserId(failRedPack.getUserId());
                            ar1.setUpdateTime(new Date());
                            ar1.setType("8");
                            ar1.setAmount(failRedPack.getPrizeMoney());
                            ar1.setNowAmount(account.getVoucherBalance());
                            ar1.setSign("1");
                            ar1.setOrderNo(failRedPack.getOrderNo());
                            ar1.setInfo(customerDao.queryById(failRedPack.getUserId()).getAgentCode() + "开拼团红包! 获得拼团余额：" + failRedPack.getPrizeMoney());
                            accountRecordDao.save(ar1);
                            // 新团，模式ID为30的
                            //ordersService.handleCollageProfit30(failRedPack.getUserId(), failRedPack.getPrizeMoney(), failRedPack.getOrderNo());
                        }
                    }
                }
            }
        }
        return ResponseServer.success("开红包成功", bd);
    }


    /**
     * 获取我的余额记录
     * 默认
     * @param userId
     * @return
     */
    @GetMapping("/getMyAccountRecord")
    public ResponseServer getMyAccountRecord(Integer userId, Integer type, Integer pageIndex){
        Map<String, Object> params = new HashMap<>();
        params.put("userId", userId);
        params.put("type", type);
        params.put("pageNum", pageIndex);
        params.put("pageSize", 10);
        InitPaging.init(params);
        List<AccountRecord> accountRecordList = accountRecordDao.queryByUserId(params);
        return ResponseServer.success("余额记录加载成功", new PageInfo<>(accountRecordList));
    }


    /**
     * 获取我的余额记录
     * 默认
     * @param userId
     * @return
     */
    @GetMapping("/getMyAccountRecord1")
    public ResponseServer getMyAccountRecord1(Integer userId){
        Map map = new HashMap();
        Customer customer = customerDao.queryById(userId);
        map.put("verifyStatus", customer.getVerifyStatus());
        map.put("achievement", customer.getAchievement());
        List<UserCoupon> ucList = userCouponDao.queryCouponByUserId(customer.getId());
        if(ucList.size() > 0){
            for(int i = 0; i < ucList.size(); i++){
                UserCoupon uc = ucList.get(i);
                if(uc.getCouponId() == 1){
                    map.put("ptVoucher", uc.getQuantity());
                }else{
                    map.put("gxVoucher", uc.getQuantity());
                }
            }
        }else{
            map.put("ptVoucher", 0);
            map.put("gxVoucher", 0);
        }
        Account account = accountDao.queryAccountByUserId(userId);
        map.put("voucherBalance", account.getVoucherBalance());
        map.put("redPacket", account.getRedPacket());
        map.put("bliss", account.getBliss());
        map.put("integral", account.getIntegral());
        return ResponseServer.success("加载成功", map);
    }


    /**
     * 获取我的余额记录
     * 筛选
     * @param userId
     * @return
     */
    @GetMapping("/getMyAccountRecord_1")
    public ResponseServer getMyAccountRecord_1(Integer userId, Integer type, Integer pageIndex){
        Map<String, Object> params = new HashMap<>();
        params.put("userId", userId);
        params.put("type", type);
        params.put("pageNum", pageIndex);
        params.put("pageSize", 10);
        InitPaging.init(params);
        List<AccountRecord> accountRecordList = accountRecordDao.queryByUserId(params);
        return ResponseServer.success("余额记录加载成功", new PageInfo<>(accountRecordList));
    }


    /**
     * 添加业绩
     * @param orders
     */
    public void addAchievement(Orders orders){
        // 添加业绩
        OrderDetails od = orderDetailsDao.queryByOrderNo(orders.getOrderNo());
        if(od != null){
            if("3".equals(od.getProductType())) {
                BigDecimal totalAmount = orders.getPayAmount(); // 实际支付的金额

                Customer customer = customerDao.queryById(orders.getOrderPersonId());
                if (customer != null) {
                    customer.setAchievement(customer.getAchievement().add(totalAmount));
                    customerDao.update(customer);
                    handleAccount2(customer.getId(), totalAmount, customer.getAchievement(), orders.getOrderNo(), customer.getAgentCode());
                    if (customer.getParentId() != null && customer.getParentId() != 1198 && customer.getLevelCopyId() != 11) {

                        Customer cu1 = customerDao.queryById(customer.getParentId()); // 一层
                        if (cu1 != null) {
                            cu1.setAchievement(cu1.getAchievement().add(totalAmount));
                            customerDao.update(cu1);
                            handleAccount2(cu1.getId(), totalAmount, cu1.getAchievement(), orders.getOrderNo(), cu1.getAgentCode());
                            if (cu1.getParentId() != null && cu1.getParentId() != 1198 && cu1.getLevelCopyId() != 11) {

                                Customer cu2 = customerDao.queryById(cu1.getParentId()); // 二层
                                if (cu2 != null) {
                                    cu2.setAchievement(cu2.getAchievement().add(totalAmount));
                                    customerDao.update(cu2);
                                    handleAccount2(cu2.getId(), totalAmount, cu2.getAchievement(), orders.getOrderNo(), cu2.getAgentCode());
                                    if (cu2.getParentId() != null && cu2.getParentId() != 1198 && cu2.getLevelCopyId() != 11) {

                                        Customer cu3 = customerDao.queryById(cu2.getParentId()); // 三层
                                        if (cu3 != null) {
                                            cu3.setAchievement(cu3.getAchievement().add(totalAmount));
                                            customerDao.update(cu3);
                                            handleAccount2(cu3.getId(), totalAmount, cu3.getAchievement(), orders.getOrderNo(), cu3.getAgentCode());
                                            if (cu3.getParentId() != null && cu3.getParentId() != 1198 && cu3.getLevelCopyId() != 11) {

                                                Customer cu4 = customerDao.queryById(cu3.getParentId()); // 四层
                                                if (cu4 != null) {
                                                    cu4.setAchievement(cu4.getAchievement().add(totalAmount));
                                                    customerDao.update(cu4);
                                                    handleAccount2(cu4.getId(), totalAmount, cu4.getAchievement(), orders.getOrderNo(), cu4.getAgentCode());
                                                    if (cu4.getParentId() != null && cu4.getParentId() != 1198 && cu4.getLevelCopyId() != 11) {

                                                        Customer cu5 = customerDao.queryById(cu4.getParentId()); // 五层
                                                        if (cu5 != null) {
                                                            cu5.setAchievement(cu5.getAchievement().add(totalAmount));
                                                            customerDao.update(cu5);
                                                            handleAccount2(cu5.getId(), totalAmount, cu5.getAchievement(), orders.getOrderNo(), cu5.getAgentCode());
                                                            if (cu5.getParentId() != null && cu5.getParentId() != 1198 && cu5.getLevelCopyId() != 11) {

                                                                Customer cu6 = customerDao.queryById(cu5.getParentId()); // 六层
                                                                if (cu6 != null) {
                                                                    cu6.setAchievement(cu6.getAchievement().add(totalAmount));
                                                                    customerDao.update(cu6);
                                                                    handleAccount2(cu6.getId(), totalAmount, cu6.getAchievement(), orders.getOrderNo(), cu6.getAgentCode());
                                                                    if (cu6.getParentId() != null && cu6.getParentId() != 1198 && cu6.getLevelCopyId() != 11) {

                                                                        Customer cu7 = customerDao.queryById(cu6.getParentId()); // 七层
                                                                        if (cu7 != null) {
                                                                            cu7.setAchievement(cu7.getAchievement().add(totalAmount));
                                                                            customerDao.update(cu7);
                                                                            handleAccount2(cu7.getId(), totalAmount, cu7.getAchievement(), orders.getOrderNo(), cu7.getAgentCode());
                                                                            if (cu7.getParentId() != null && cu7.getParentId() != 1198 && cu7.getLevelCopyId() != 11) {

                                                                                Customer cu8 = customerDao.queryById(cu7.getParentId()); // 八层
                                                                                if (cu8 != null) {
                                                                                    cu8.setAchievement(cu8.getAchievement().add(totalAmount));
                                                                                    customerDao.update(cu8);
                                                                                    handleAccount2(cu8.getId(), totalAmount, cu8.getAchievement(), orders.getOrderNo(), cu8.getAgentCode());
                                                                                    if (cu8.getParentId() != null && cu8.getParentId() != 1198 && cu8.getLevelCopyId() != 11) {

                                                                                        Customer cu9 = customerDao.queryById(cu8.getParentId()); // 九层
                                                                                        if (cu9 != null) {
                                                                                            cu9.setAchievement(cu9.getAchievement().add(totalAmount));
                                                                                            customerDao.update(cu9);
                                                                                            handleAccount2(cu9.getId(), totalAmount, cu9.getAchievement(), orders.getOrderNo(), cu9.getAgentCode());
                                                                                            if (cu9.getParentId() != null && cu9.getParentId() != 1198 && cu9.getLevelCopyId() != 11) {

                                                                                                Customer cu10 = customerDao.queryById(cu9.getParentId()); // 十层
                                                                                                if (cu10 != null) {
                                                                                                    cu10.setAchievement(cu10.getAchievement().add(totalAmount));
                                                                                                    customerDao.update(cu10);
                                                                                                    handleAccount2(cu10.getId(), totalAmount, cu10.getAchievement(), orders.getOrderNo(), cu10.getAgentCode());
                                                                                                    if (cu10.getParentId() != null && cu10.getParentId() != 1198 && cu10.getLevelCopyId() != 11) {

                                                                                                        Customer cu11 = customerDao.queryById(cu10.getParentId()); // 十一层
                                                                                                        if (cu11 != null) {
                                                                                                            cu11.setAchievement(cu11.getAchievement().add(totalAmount));
                                                                                                            customerDao.update(cu11);
                                                                                                            handleAccount2(cu11.getId(), totalAmount, cu11.getAchievement(), orders.getOrderNo(), cu11.getAgentCode());
                                                                                                            if (cu11.getParentId() != null && cu11.getParentId() != 1198 && cu11.getLevelCopyId() != 11) {

                                                                                                                Customer cu12 = customerDao.queryById(cu11.getParentId()); // 十二层
                                                                                                                if (cu12 != null) {
                                                                                                                    cu12.setAchievement(cu12.getAchievement().add(totalAmount));
                                                                                                                    customerDao.update(cu12);
                                                                                                                    handleAccount2(cu12.getId(), totalAmount, cu12.getAchievement(), orders.getOrderNo(), cu12.getAgentCode());
                                                                                                                    if (cu12.getParentId() != null && cu12.getParentId() != 1198 && cu12.getLevelCopyId() != 11) {

                                                                                                                        Customer cu13 = customerDao.queryById(cu12.getParentId()); // 十三层
                                                                                                                        if (cu13 != null) {
                                                                                                                            cu13.setAchievement(cu13.getAchievement().add(totalAmount));
                                                                                                                            customerDao.update(cu13);
                                                                                                                            handleAccount2(cu13.getId(), totalAmount, cu13.getAchievement(), orders.getOrderNo(), cu13.getAgentCode());
                                                                                                                            if (cu13.getParentId() != null && cu13.getParentId() != 1198 && cu13.getLevelCopyId() != 11) {

                                                                                                                                Customer cu14 = customerDao.queryById(cu13.getParentId()); // 十四层
                                                                                                                                if (cu14 != null) {
                                                                                                                                    cu14.setAchievement(cu14.getAchievement().add(totalAmount));
                                                                                                                                    customerDao.update(cu14);
                                                                                                                                    handleAccount2(cu14.getId(), totalAmount, cu14.getAchievement(), orders.getOrderNo(), cu14.getAgentCode());
                                                                                                                                    if (cu14.getParentId() != null && cu14.getParentId() != 1198 && cu14.getLevelCopyId() != 11) {

                                                                                                                                        Customer cu15 = customerDao.queryById(cu14.getParentId()); // 十五层
                                                                                                                                        if (cu15 != null) {
                                                                                                                                            cu15.setAchievement(cu15.getAchievement().add(totalAmount));
                                                                                                                                            customerDao.update(cu15);
                                                                                                                                            handleAccount2(cu15.getId(), totalAmount, cu15.getAchievement(), orders.getOrderNo(), cu15.getAgentCode());
                                                                                                                                            if (cu15.getParentId() != null && cu15.getParentId() != 1198 && cu15.getLevelCopyId() != 11) {

                                                                                                                                                Customer cu16 = customerDao.queryById(cu15.getParentId()); // 十六层
                                                                                                                                                if (cu16 != null) {
                                                                                                                                                    cu16.setAchievement(cu16.getAchievement().add(totalAmount));
                                                                                                                                                    customerDao.update(cu16);
                                                                                                                                                    handleAccount2(cu16.getId(), totalAmount, cu16.getAchievement(), orders.getOrderNo(), cu16.getAgentCode());
                                                                                                                                                    if (cu16.getParentId() != null && cu16.getParentId() != 1198 && cu16.getLevelCopyId() != 11) {

                                                                                                                                                        Customer cu17 = customerDao.queryById(cu16.getParentId()); // 十七层
                                                                                                                                                        if (cu17 != null) {
                                                                                                                                                            cu17.setAchievement(cu17.getAchievement().add(totalAmount));
                                                                                                                                                            customerDao.update(cu17);
                                                                                                                                                            handleAccount2(cu17.getId(), totalAmount, cu17.getAchievement(), orders.getOrderNo(), cu17.getAgentCode());
                                                                                                                                                            if (cu17.getParentId() != null && cu17.getParentId() != 1198 && cu17.getLevelCopyId() != 11) {

                                                                                                                                                                Customer cu18 = customerDao.queryById(cu17.getParentId()); // 十八层
                                                                                                                                                                if(cu18 != null){
                                                                                                                                                                    cu18.setAchievement(cu18.getAchievement().add(totalAmount));
                                                                                                                                                                    customerDao.update(cu18);
                                                                                                                                                                    handleAccount2(cu18.getId(), totalAmount, cu18.getAchievement(), orders.getOrderNo(), cu18.getAgentCode());
                                                                                                                                                                    if (cu18.getParentId() != null && cu18.getParentId() != 1198 && cu18.getLevelCopyId() != 11) {

                                                                                                                                                                        Customer cu19 = customerDao.queryById(cu18.getParentId()); // 十九层
                                                                                                                                                                        if(cu19 != null){
                                                                                                                                                                            cu19.setAchievement(cu19.getAchievement().add(totalAmount));
                                                                                                                                                                            customerDao.update(cu19);
                                                                                                                                                                            handleAccount2(cu19.getId(), totalAmount, cu19.getAchievement(), orders.getOrderNo(), cu19.getAgentCode());
                                                                                                                                                                            if (cu19.getParentId() != null && cu19.getParentId() != 1198 && cu19.getLevelCopyId() != 11) {

                                                                                                                                                                                Customer cu20 = customerDao.queryById(cu19.getParentId()); // 二十层
                                                                                                                                                                                if(cu20 != null){
                                                                                                                                                                                    cu20.setAchievement(cu20.getAchievement().add(totalAmount));
                                                                                                                                                                                    customerDao.update(cu20);
                                                                                                                                                                                    handleAccount2(cu20.getId(), totalAmount, cu20.getAchievement(), orders.getOrderNo(), cu20.getAgentCode());
                                                                                                                                                                                    if (cu20.getParentId() != null && cu20.getParentId() != 1198 && cu20.getLevelCopyId() != 11) {

                                                                                                                                                                                        Customer cu21 = customerDao.queryById(cu20.getParentId()); // 二十一层
                                                                                                                                                                                        if(cu21 != null){
                                                                                                                                                                                            cu21.setAchievement(cu21.getAchievement().add(totalAmount));
                                                                                                                                                                                            customerDao.update(cu21);
                                                                                                                                                                                            handleAccount2(cu21.getId(), totalAmount, cu21.getAchievement(), orders.getOrderNo(), cu21.getAgentCode());
                                                                                                                                                                                            if (cu21.getParentId() != null && cu21.getParentId() != 1198 && cu21.getLevelCopyId() != 11) {

                                                                                                                                                                                                Customer cu22 = customerDao.queryById(cu21.getParentId()); // 二十二层
                                                                                                                                                                                                if(cu22 != null){
                                                                                                                                                                                                    cu22.setAchievement(cu22.getAchievement().add(totalAmount));
                                                                                                                                                                                                    customerDao.update(cu22);
                                                                                                                                                                                                    handleAccount2(cu22.getId(), totalAmount, cu22.getAchievement(), orders.getOrderNo(), cu22.getAgentCode());
                                                                                                                                                                                                    if (cu22.getParentId() != null && cu22.getParentId() != 1198 && cu22.getLevelCopyId() != 11) {

                                                                                                                                                                                                        Customer cu23 = customerDao.queryById(cu22.getParentId()); // 二十三层
                                                                                                                                                                                                        if(cu23 != null){
                                                                                                                                                                                                            cu23.setAchievement(cu23.getAchievement().add(totalAmount));
                                                                                                                                                                                                            customerDao.update(cu23);
                                                                                                                                                                                                            handleAccount2(cu23.getId(), totalAmount, cu23.getAchievement(), orders.getOrderNo(), cu23.getAgentCode());
                                                                                                                                                                                                            if (cu23.getParentId() != null && cu23.getParentId() != 1198 && cu23.getLevelCopyId() != 11) {

                                                                                                                                                                                                                Customer cu24 = customerDao.queryById(cu23.getParentId()); // 二十四层
                                                                                                                                                                                                                if(cu24 != null){
                                                                                                                                                                                                                    cu24.setAchievement(cu24.getAchievement().add(totalAmount));
                                                                                                                                                                                                                    customerDao.update(cu24);
                                                                                                                                                                                                                    handleAccount2(cu24.getId(), totalAmount, cu24.getAchievement(), orders.getOrderNo(), cu24.getAgentCode());
                                                                                                                                                                                                                    if (cu24.getParentId() != null && cu24.getParentId() != 1198 && cu24.getLevelCopyId() != 11) {

                                                                                                                                                                                                                        Customer cu25 = customerDao.queryById(cu24.getParentId()); // 二十五层
                                                                                                                                                                                                                        if(cu25 != null){
                                                                                                                                                                                                                            cu25.setAchievement(cu25.getAchievement().add(totalAmount));
                                                                                                                                                                                                                            customerDao.update(cu25);
                                                                                                                                                                                                                            handleAccount2(cu25.getId(), totalAmount, cu25.getAchievement(), orders.getOrderNo(), cu25.getAgentCode());

                                                                                                                                                                                                                            if (cu25.getParentId() != null && cu25.getParentId() != 1198 && cu25.getLevelCopyId() != 11) {

                                                                                                                                                                                                                                Customer cu26 = customerDao.queryById(cu25.getParentId()); // 二十六层
                                                                                                                                                                                                                                if(cu26 != null){
                                                                                                                                                                                                                                    cu26.setAchievement(cu26.getAchievement().add(totalAmount));
                                                                                                                                                                                                                                    customerDao.update(cu26);
                                                                                                                                                                                                                                    handleAccount2(cu26.getId(), totalAmount, cu26.getAchievement(), orders.getOrderNo(), cu26.getAgentCode());
                                                                                                                                                                                                                                }
                                                                                                                                                                                                                            }
                                                                                                                                                                                                                        }
                                                                                                                                                                                                                    }
                                                                                                                                                                                                                }
                                                                                                                                                                                                            }
                                                                                                                                                                                                        }
                                                                                                                                                                                                    }
                                                                                                                                                                                                }
                                                                                                                                                                                            }
                                                                                                                                                                                        }
                                                                                                                                                                                    }
                                                                                                                                                                                }
                                                                                                                                                                            }
                                                                                                                                                                        }
                                                                                                                                                                    }
                                                                                                                                                                }
                                                                                                                                                            }
                                                                                                                                                        }
                                                                                                                                                    }
                                                                                                                                                }
                                                                                                                                            }
                                                                                                                                        }
                                                                                                                                    }
                                                                                                                                }
                                                                                                                            }
                                                                                                                        }
                                                                                                                    }
                                                                                                                }
                                                                                                            }
                                                                                                        }
                                                                                                    }
                                                                                                }
                                                                                            }
                                                                                        }
                                                                                    }
                                                                                }
                                                                            }
                                                                        }
                                                                    }
                                                                }
                                                            }
                                                        }
                                                    }
                                                }
                                            }
                                        }
                                    }
                                }
                            }
                        }
                    }
                }
            }
        }else{

        }
    }


    /**
     * 获取共享专区
     * @return
     */
    @GetMapping("/getShareClassifyData")
    public ResponseServer getShareClassifyData(){
        List<Classify> classifyList = classifyDao.queryByIsShare();
        return ResponseServer.success("共享专区加载成功", classifyList);
    }


    /**
     * 获取共享专区下相应的产品信息
     * @param classifyId
     * @return
     */
    @GetMapping("/getProductByClassifyId")
    public ResponseServer getProductByClassifyId(Integer classifyId){
        List<Product> productList = productDao.queryProductByClassifyId(classifyId);
        return ResponseServer.success("共享专区下产品加载成功", productList);
    }


    /**
     * 转券
     * @param outUserId
     * @param intoUserId
     * @param voucherBalance
     * @param type      0=余额，1=共享券，2=拼团券
     * @return
     */
    @PostMapping("/turnVoucherBalance")
    public ResponseServer turnVoucherBalance(Integer outUserId, Integer intoUserId, BigDecimal voucherBalance, String type){
        if(voucherBalance.doubleValue() <= 0){
            return ResponseServer.error("转券数量需大于零");
        }
        if("0".equals(type)){
            Account intoAcc = accountDao.queryAccountByUserId(intoUserId);
            if(intoAcc == null){
                return ResponseServer.error("进账人账户错误，请联系管理员");
            }
            Account outAcc = accountDao.queryAccountByUserId(outUserId);
            if(outAcc == null){
                return ResponseServer.error("出账人账户错误，请联系管理员");
            }
            if(outAcc.getVoucherBalance().doubleValue() <= 0 || outAcc.getVoucherBalance().doubleValue() < voucherBalance.doubleValue()){
                return ResponseServer.error("余额不足");
            }
            outAcc.setVoucherBalance(outAcc.getVoucherBalance().subtract(voucherBalance));
            accountDao.update(outAcc);
            intoAcc.setVoucherBalance(intoAcc.getVoucherBalance().add(voucherBalance));
            accountDao.update(intoAcc);
            AccountRecord ar1 = new AccountRecord();
            ar1.setIntoUserId(intoUserId);
            ar1.setUpdateTime(new Date());
            ar1.setType("0");
            ar1.setAmount(voucherBalance);
            ar1.setNowAmount(intoAcc.getVoucherBalance());
            ar1.setSign("1");
            ar1.setInfo(customerDao.queryById(outUserId).getAgentCode() + "转余额给你：" + voucherBalance);
            accountRecordDao.save(ar1);
            AccountRecord ar2 = new AccountRecord();
            ar2.setOutUserId(outUserId);
            ar2.setUpdateTime(new Date());
            ar2.setType("0");
            ar2.setAmount(voucherBalance);
            ar2.setNowAmount(outAcc.getVoucherBalance());
            ar2.setSign("2");
            ar2.setInfo("您转余额给" + customerDao.queryById(intoUserId).getAgentCode() + "：" + voucherBalance);
            accountRecordDao.save(ar2);
            return ResponseServer.success("转余额成功");
        }else if("1".equals(type)){
            int quantity = (int)voucherBalance.doubleValue();
            UserCoupon outCoupon = userCouponDao.queryUserCouponByIds(outUserId, "1"); // 出账人的共享券
            if(outCoupon != null){
                if(outCoupon.getQuantity() >= quantity){
                    UserCoupon intoCoupon = userCouponDao.queryUserCouponByIds(intoUserId, "1"); // 进账人的共享券
                    if(intoCoupon != null){
                        intoCoupon.setQuantity(quantity + intoCoupon.getQuantity());
                        userCouponDao.update(intoCoupon);

                        AccountRecord ar1 = new AccountRecord();
                        ar1.setIntoUserId(intoUserId);
                        ar1.setUpdateTime(new Date());
                        ar1.setType("6");
                        ar1.setAmount(new BigDecimal(quantity));
                        ar1.setNowAmount(new BigDecimal(intoCoupon.getQuantity()));
                        ar1.setSign("1");
                        ar1.setInfo(customerDao.queryById(outUserId).getAgentCode() + "转共享券给你：" + quantity);
                        accountRecordDao.save(ar1);

                        outCoupon.setQuantity(outCoupon.getQuantity() - quantity);
                        userCouponDao.update(outCoupon);
                        AccountRecord ar2 = new AccountRecord();
                        ar2.setOutUserId(outUserId);
                        ar2.setUpdateTime(new Date());
                        ar2.setType("6");
                        ar2.setAmount(new BigDecimal(quantity));
                        ar2.setNowAmount(new BigDecimal(outCoupon.getQuantity()));
                        ar2.setSign("2");
                        ar2.setInfo("您转共享券给" + customerDao.queryById(intoUserId).getAgentCode() + "：" + voucherBalance);
                        accountRecordDao.save(ar2);
                    }else{
                        UserCoupon newIntoCoupon = new UserCoupon();
                        newIntoCoupon.setCouponId(outCoupon.getCouponId());
                        newIntoCoupon.setQuantity(quantity);
                        newIntoCoupon.setUpdateTime(new Date());
                        newIntoCoupon.setUserId(intoUserId);
                        userCouponDao.save(newIntoCoupon);

                        AccountRecord ar1 = new AccountRecord();
                        ar1.setIntoUserId(intoUserId);
                        ar1.setUpdateTime(new Date());
                        ar1.setType("6");
                        ar1.setAmount(new BigDecimal(quantity));
                        ar1.setNowAmount(new BigDecimal(newIntoCoupon.getQuantity()));
                        ar1.setSign("1");
                        ar1.setInfo(customerDao.queryById(outUserId).getAgentCode() + "转共享券给你：" + quantity);
                        accountRecordDao.save(ar1);

                        outCoupon.setQuantity(outCoupon.getQuantity() - quantity);
                        userCouponDao.update(outCoupon);
                        AccountRecord ar2 = new AccountRecord();
                        ar2.setOutUserId(outUserId);
                        ar2.setUpdateTime(new Date());
                        ar2.setType("6");
                        ar2.setAmount(new BigDecimal(quantity));
                        ar2.setNowAmount(new BigDecimal(outCoupon.getQuantity()));
                        ar2.setSign("2");
                        ar2.setInfo("您转共享券给" + customerDao.queryById(intoUserId).getAgentCode() + "：" + voucherBalance);
                        accountRecordDao.save(ar2);
                    }
                    return ResponseServer.success("转共享券成功");
                }else{
                    return ResponseServer.error("共享券数量不足，无法转赠");
                }
            }else{
                return ResponseServer.error("共享券数量不足，无法转赠");
            }
        }else if("2".equals(type)){
            int quantity = (int)voucherBalance.doubleValue();
            UserCoupon outCoupon = userCouponDao.queryUserCouponByIds(outUserId, "0"); // 出账人的拼团券
            if(outCoupon != null){
                if(outCoupon.getQuantity() >= quantity){
                    UserCoupon intoCoupon = userCouponDao.queryUserCouponByIds(intoUserId, "0"); // 进账人的拼团券
                    if(intoCoupon != null){
                        intoCoupon.setQuantity(quantity + intoCoupon.getQuantity());
                        userCouponDao.update(intoCoupon);

                        AccountRecord ar1 = new AccountRecord();
                        ar1.setIntoUserId(intoUserId);
                        ar1.setUpdateTime(new Date());
                        ar1.setType("5");
                        ar1.setAmount(new BigDecimal(quantity));
                        ar1.setNowAmount(new BigDecimal(intoCoupon.getQuantity()));
                        ar1.setSign("1");
                        ar1.setInfo(customerDao.queryById(outUserId).getAgentCode() + "转拼团券给你：" + quantity);
                        accountRecordDao.save(ar1);

                        outCoupon.setQuantity(outCoupon.getQuantity() - quantity);
                        userCouponDao.update(outCoupon);
                        AccountRecord ar2 = new AccountRecord();
                        ar2.setOutUserId(outUserId);
                        ar2.setUpdateTime(new Date());
                        ar2.setType("5");
                        ar2.setAmount(new BigDecimal(quantity));
                        ar2.setNowAmount(new BigDecimal(outCoupon.getQuantity()));
                        ar2.setSign("2");
                        ar2.setInfo("您转拼团券给" + customerDao.queryById(intoUserId).getAgentCode() + "：" + voucherBalance);
                        accountRecordDao.save(ar2);
                    }else{
                        UserCoupon newIntoCoupon = new UserCoupon();
                        newIntoCoupon.setCouponId(outCoupon.getCouponId());
                        newIntoCoupon.setQuantity(quantity);
                        newIntoCoupon.setUpdateTime(new Date());
                        newIntoCoupon.setUserId(intoUserId);
                        userCouponDao.save(newIntoCoupon);

                        AccountRecord ar1 = new AccountRecord();
                        ar1.setIntoUserId(intoUserId);
                        ar1.setUpdateTime(new Date());
                        ar1.setType("5");
                        ar1.setAmount(new BigDecimal(quantity));
                        ar1.setNowAmount(new BigDecimal(newIntoCoupon.getQuantity()));
                        ar1.setSign("1");
                        ar1.setInfo(customerDao.queryById(outUserId).getAgentCode() + "转拼团券给你：" + quantity);
                        accountRecordDao.save(ar1);

                        outCoupon.setQuantity(outCoupon.getQuantity() - quantity);
                        userCouponDao.update(outCoupon);
                        AccountRecord ar2 = new AccountRecord();
                        ar2.setOutUserId(outUserId);
                        ar2.setUpdateTime(new Date());
                        ar2.setType("5");
                        ar2.setAmount(new BigDecimal(quantity));
                        ar2.setNowAmount(new BigDecimal(outCoupon.getQuantity()));
                        ar2.setSign("2");
                        ar2.setInfo("您转拼团券给" + customerDao.queryById(intoUserId).getAgentCode() + "：" + voucherBalance);
                        accountRecordDao.save(ar2);
                    }

                    return ResponseServer.success("转拼团券成功");
                }else{
                    return ResponseServer.error("拼团券数量不足，无法转赠");
                }
            }else{
                return ResponseServer.error("拼团券数量不足，无法转赠");
            }
        }else{
            return ResponseServer.error("转账失败TYPE问题，请联系管理员");
        }
    }


    /**
     * 判断用户是否实名认证
     * @param userId
     * @return
     */
    @GetMapping("/getCustomerByVerifyStatus")
    public ResponseServer getCustomerByVerifyStatus(Integer userId){
        Customer customer = customerDao.queryById(userId);
        if(customer != null){
            if("1".equals(customer.getVerifyStatus())){
                return ResponseServer.success("已实名认证");
            }
        }
        return ResponseServer.error("未实名认证");
    }


    /**
     * 我的优惠券信息
     * @param userId
     * @return
     */
    @GetMapping("/getMyCouponData")
    public ResponseServer getMyCouponData(Integer userId){
        List<UserCouponVO> userCouponList = userCouponDao.queryUserCouponByUserId(userId);
        return ResponseServer.success(userCouponList);
    }


    /**
     * 加载共享券信息
     * @param couponId
     * @param userId
     * @return
     */
    @GetMapping("/getCouponData")
    public ResponseServer getCouponData(Integer couponId, Integer userId){

        UserCoupon userCoupon = userCouponDao.queryByUserIdAndCouponId(userId, couponId);
        if(userCoupon == null){
            UserCoupon newUC = new UserCoupon();
            newUC.setUserId(userId);
            newUC.setCouponId(couponId);
            newUC.setQuantity(0);
            newUC.setUpdateTime(new Date());
            userCouponDao.save(newUC);
        }

        UserCouponVO userCouponList = userCouponDao.queryCouponByIds(couponId, userId);

        return ResponseServer.success(userCouponList);
    }


    /**
     * 加载拼团模式数据
     * @return
     */
    @GetMapping("/getCollageModeData")
    public ResponseServer getCollageModeData(){
        List<CollageMode> collageModeList = collageModeDao.queryCollageModeByType();
        return ResponseServer.success(collageModeList);
    }


    /**
     * 加载拼团模式下的产品列表数据
     * @param collageModeId
     * @param userId
     * @param pageIndex
     * @return
     */
    @GetMapping("/getCollageModeProductData")
    public ResponseServer getCollageModeProductData(Integer collageModeId, Integer userId, Integer pageIndex){
        Map<String, Object> params = new HashMap<>();
        params.put("pageNum", pageIndex);
        params.put("pageSize", 6);
        params.put("collageModeId",collageModeId);
        InitPaging.init(params);
        List<Product> productList = productDao.queryProductByModeId(params);
        if(collageModeId == 2 && userId != 3) {
            List<CollageInRecord2> cir2List = collageInRecord2Dao.queryCir2ByUserId(userId);
            if (cir2List.size() > 0) {
                if (productList.size() > 0) {
                    for (int j = 0; j < productList.size(); j++) {
                        Product product = productList.get(j);
                        for (int i = 0; i < cir2List.size(); i++) {
                            CollageInRecord2 cir2 = cir2List.get(i);
                            if (product.getId().equals(cir2.getProductId())) {
                                product.setQuantity(cir2.getTotalQuantity());
                                //product.setUseQuantity(cir2.getTotalQuantity());
                                // TODO 将6改成3
                                int num = (int) (cir2.getTotalQuantity() / (float) 3 * 100);
                                product.setPercentage((double) num);
                                break;
                            } else {
                                product.setQuantity(0);
                                product.setPercentage(0.0);
                            }
                        }
                    }
                }
            }
        }else if(collageModeId == 3 && userId != 3){
            List<CollageInRecord3Copy> cir3CopyList = collageInRecord3CopyDao.queryCir3CopyByUserId(userId);
            if(cir3CopyList.size() > 0){
                if (productList.size() > 0) {
                    for (int j = 0; j < productList.size(); j++) {
                        Product product = productList.get(j);
                        for (int i = 0; i < cir3CopyList.size(); i++) {
                            CollageInRecord3Copy cir3Copy = cir3CopyList.get(i);
                            if (product.getId().equals(cir3Copy.getProductId())) {
                                product.setQuantity(cir3Copy.getTotalQuantity());
                                 // TODO 将12改成3
                                int num = (int) (cir3Copy.getTotalQuantity()/(float)3*100);
                                product.setPercentage((double) num);
                                break;
                            } else {
                                product.setQuantity(0);
                                product.setPercentage(0.0);
                            }
                        }
                    }
                }
            }
        }else{
            if(productList.size() > 0){
                for(int j = 0; j < productList.size(); j++){
                    Product product = productList.get(j);
                    product.setQuantity(0);
                    product.setPercentage(0.0);
                }
            }
        }
        return ResponseServer.success(new PageInfo<>(productList));
    }


    /**
     * 加载拼团游戏模式数据
     * @return
     */
    @GetMapping("/getCollageModeGameData")
    public ResponseServer getCollageModeGameData(){
        List<CollageMode> collageModeList = collageModeDao.queryCollageModeByGameType();
        return ResponseServer.success(collageModeList);
    }


    /**
     * 加载拼团游戏模式数据
     * @return
     */
    @GetMapping("/getCollageModeGameByIdData")
    public ResponseServer getCollageModeGameByIdData(Integer collageModeId){
        Map map = new HashMap();
        CollageMode collageMode = collageModeDao.queryById(collageModeId);
        map.put("collageMode", collageMode);
        List<ModeProductUserDTO> mpuDTOList = modeProductGameDao.queryByModeIdByStatus(collageModeId);
        if(mpuDTOList.size() > 0){
            for(int i = 0; i < mpuDTOList.size(); i++){
                ModeProductUserDTO dto = mpuDTOList.get(i);
                ModeProductUserDTO mpg = modeProductGameDao.queryByIds_1(collageModeId, dto.getId());
                if(mpg != null){
                    CollageUserGame cug = collageUserGameDao.queryByModeId(mpg.getId());
                    if(cug != null){
                        dto.setPkUserId(cug.getUserId());
                        dto.setPkHeadImg(customerDao.queryById(cug.getUserId()).getHeadImg());
                    }
                }
            }
        }
        map.put("mpuDTOList", mpuDTOList);
        return ResponseServer.success(map);
    }


    /**
     * 加载拼团模式下游戏的产品列表数据
     * @param collageModeId
     * @return
     */
    @GetMapping("/getCollageModeGameProductData")
    public ResponseServer getCollageModeGameProductData(Integer collageModeId){
        List<Product> productList = productDao.queryProductGameByModeId(collageModeId);
        return ResponseServer.success(productList);
    }


    /**
     * 查看挑战结果
     * @param orderNo
     * @return
     */
    @GetMapping("/getWinLoseRecordData")
    public ResponseServer getWinLoseRecordData(String orderNo){
        WinLoseRecord winLoseRecord = winLoseRecordDao.queryByOrderNo(orderNo);
        return ResponseServer.success(winLoseRecord);
    }


    /**
     * 加载PK数据
     * @param modeProductId
     * @return
     */
    @GetMapping("/getPKData")
    public ResponseServer getPKData(Integer modeProductId){
        PKDTO dto = new PKDTO();

        ModeProductGame mpg = modeProductGameDao.queryById(modeProductId);
        CollageUserGame cug = collageUserGameDao.queryByModeId(mpg.getId());
        Customer customer = customerDao.queryById(cug.getUserId());

        dto.setPkGameId(mpg.getId());
        dto.setPkHeadImg(customer.getHeadImg());
        dto.setPkUserId(customer.getId());

        ModeProductGame mpg1 = modeProductGameDao.queryById(mpg.getParentId());
        CollageUserGame cug1 = collageUserGameDao.queryByModeId(mpg1.getId());
        Customer customer1 = customerDao.queryById(cug1.getUserId());

        dto.setFaGameId(mpg1.getId());
        dto.setFaHeadImg(customer1.getHeadImg());
        dto.setFaUserId(customer1.getId());

        dto.setCollageModeId(mpg.getModeId());

        return ResponseServer.success(dto);
    }


    /**
     * 处理PK数据
     * @param faUserId
     * @param challengerState - 挑战者的输赢状态
     * @param faGameId
     * @param pkUserId
     * @param masterState - 发起者的输赢状态
     * @param pkGameId
     * @return
     */
    @GetMapping("/handlePKData")
    public ResponseServer handlePKData(Integer pkUserId, String challengerState, Integer pkGameId,
                                       Integer faUserId, String masterState, Integer faGameId,
                                       String pkImg, String faImg){

        ModeProductGame mpg = modeProductGameDao.queryById(faGameId);
        if(mpg != null){
            if("0".equals(mpg.getStatus())){
                ModeProductGame mpg1 = modeProductGameDao.queryById(pkGameId);
                if(mpg1 != null){
                    if("0".equals(mpg1.getStatus()) && mpg1.getParentId().equals(mpg.getId())){
                        if("1".equals(masterState)){
                            // 发起者赢了
                            Orders o = ordersDao.queryByGameId(faGameId, faUserId);
                            if(o != null){
                                o.setDealStatus("1"); // 赢了修改订单为代发货
                                ordersDao.update(o);

                                mpg.setStatus("1"); // 发起者赢了 团为成功
                                modeProductGameDao.update(mpg);

                                mpg1.setStatus("1"); // 挑战者的团也为成功 准备退款
                                modeProductGameDao.update(mpg1);

                                Product product = productDao.queryById(o.getProductId());

                                // 赢的人发货

                                Account acc = accountDao.queryAccountByUserId(o.getOrderPersonId());
                                // 送3个极乐值
                                acc.setBliss(acc.getBliss() + 3);
                                // 送等额的积分
                                int give = (int)Math.round(o.getPayAmount().doubleValue());
                                acc.setIntegral(acc.getIntegral() + give);
                                // 拼中也送红包余额
                                acc.setVoucherBalance(acc.getVoucherBalance().add(product.getVoucher1()));
                                accountDao.update(acc);

                                AccountRecord ar3 = new AccountRecord();
                                ar3.setIntoUserId(o.getOrderPersonId());
                                ar3.setOrderNo(o.getOrderNo());
                                ar3.setType("2");
                                ar3.setSign("1");
                                ar3.setUpdateTime(new Date());
                                ar3.setAmount(new BigDecimal(3));
                                ar3.setNowAmount(new BigDecimal(acc.getBliss()));
                                ar3.setInfo(customerDao.queryById(o.getOrderPersonId()).getAgentCode() + "参团成功! PK赢了获得极乐值：" + 3);
                                accountRecordDao.save(ar3);

                                AccountRecord ar3_1 = new AccountRecord();
                                ar3_1.setIntoUserId(o.getOrderPersonId());
                                ar3_1.setOrderNo(o.getOrderNo());
                                ar3_1.setType("1");
                                ar3_1.setSign("1");
                                ar3_1.setUpdateTime(new Date());
                                ar3_1.setAmount(new BigDecimal(give));
                                ar3_1.setNowAmount(new BigDecimal(acc.getIntegral()));
                                ar3_1.setInfo(customerDao.queryById(o.getOrderPersonId()).getAgentCode() + "参团成功! PK赢了获得积分：" + give);
                                accountRecordDao.save(ar3_1);

                                AccountRecord ar3_2 = new AccountRecord();
                                ar3_2.setIntoUserId(o.getOrderPersonId());
                                ar3_2.setUpdateTime(new Date());
                                ar3_2.setType("0");
                                ar3_2.setAmount(product.getVoucher1());
                                ar3_2.setNowAmount(acc.getVoucherBalance());
                                ar3_2.setSign("1");
                                ar3_2.setOrderNo(o.getOrderNo());
                                ar3_2.setInfo(customerDao.queryById(o.getOrderPersonId()).getAgentCode() + "参团成功! PK赢了获得红包：" + product.getVoucher1());
                                accountRecordDao.save(ar3_2);

                                // 存储输赢记录
                                WinLoseRecord wlr = winLoseRecordDao.queryByOrderNo(o.getOrderNo());
                                if(wlr == null){
                                    WinLoseRecord newWlr = new WinLoseRecord();
                                    newWlr.setOrderNo(o.getOrderNo());
                                    newWlr.setFaUserId(faUserId);
                                    newWlr.setFaImg(faImg);
                                    newWlr.setFaStatus(masterState);
                                    newWlr.setFaUserImg(customerDao.queryById(faUserId).getHeadImg());
                                    newWlr.setPkUserId(pkUserId);
                                    newWlr.setPkImg(pkImg);
                                    newWlr.setPkStatus(challengerState);
                                    newWlr.setPkUserImg(customerDao.queryById(pkUserId).getHeadImg());
                                    winLoseRecordDao.save(newWlr);
                                }

                                // 处理参与拼团后的利润分配
                                ordersCopyService.handleCollageProfit(o.getOrderPersonId(), product.getVoucher1(), o.getOrderNo());

                                // 输的人拿余额 退款 走人
                                Orders o1 = ordersDao.queryByGameId_1(pkGameId, pkUserId);
                                if(o1 != null){
                                    o1.setDealStatus("4"); // 交易关闭
                                    o1.setRefundStatus("2"); // 退款成功
                                    o1.setPayStatus("3"); // 已退款
                                    ordersDao.update(o1);

                                    Product p = productDao.queryById(o1.getProductId());

                                    Account acc1 = accountDao.queryAccountByUserId(o1.getOrderPersonId());
                                    acc1.setVoucherBalance(acc1.getVoucherBalance().add(o1.getPayAmount()));
                                    acc1.setVoucherBalance(acc1.getVoucherBalance().add(p.getVoucher()));
                                    accountDao.update(acc1);

                                    AccountRecord ar1_1 = new AccountRecord();
                                    ar1_1.setIntoUserId(o1.getOrderPersonId());
                                    ar1_1.setUpdateTime(new Date());
                                    ar1_1.setType("0");
                                    ar1_1.setAmount(o1.getPayAmount());
                                    ar1_1.setNowAmount(acc1.getVoucherBalance());
                                    ar1_1.setSign("1");
                                    ar1_1.setOrderNo(o1.getOrderNo());
                                    ar1_1.setInfo(customerDao.queryById(o1.getOrderPersonId()).getAgentCode() + "参团成功! PK输了,支付金额退回至余额：" + o1.getPayAmount());
                                    accountRecordDao.save(ar1_1);

                                    AccountRecord ar1_2 = new AccountRecord();
                                    ar1_2.setIntoUserId(o1.getOrderPersonId());
                                    ar1_2.setUpdateTime(new Date());
                                    ar1_2.setType("0");
                                    ar1_2.setAmount(p.getVoucher());
                                    ar1_2.setNowAmount(acc1.getVoucherBalance());
                                    ar1_2.setSign("1");
                                    ar1_2.setOrderNo(o1.getOrderNo());
                                    ar1_2.setInfo(customerDao.queryById(o1.getOrderPersonId()).getAgentCode() + "参团成功! PK输了,送您红包：" + p.getVoucher());
                                    accountRecordDao.save(ar1_2);

                                    BigDecimal couponAmount = null;
                                    if(o1.getCouponAmount() == null){
                                        couponAmount = new BigDecimal(0);
                                    }else{
                                        couponAmount = o1.getCouponAmount();
                                    }
                                    if(couponAmount.doubleValue() > 0){
                                        UserCoupon uc = userCouponDao.queryByUserIdAndCouponId(o1.getOrderPersonId(), 1); // 拼团券
                                        if(uc != null){
                                            int couponQuantity = (int) (couponAmount.doubleValue() / 9.9);
                                            uc.setQuantity(uc.getQuantity() + couponQuantity);
                                            userCouponDao.update(uc);

                                            AccountRecord ar2 = new AccountRecord();
                                            ar2.setIntoUserId(o1.getOrderPersonId());
                                            ar2.setUpdateTime(new Date());
                                            ar2.setType("5"); // 拼团券
                                            ar2.setAmount(new BigDecimal(couponQuantity));
                                            ar2.setNowAmount(new BigDecimal(uc.getQuantity()));
                                            ar2.setSign("1");
                                            ar2.setOrderNo(o1.getOrderNo());
                                            ar2.setInfo(customerDao.queryById(o1.getOrderPersonId()).getAgentCode() + "参团成功! 未抽中,拼团券退回：" + couponQuantity);
                                            accountRecordDao.save(ar2);
                                        }
                                    }

                                    // 存储输赢记录
                                    WinLoseRecord wlr1 = winLoseRecordDao.queryByOrderNo(o1.getOrderNo());
                                    if(wlr1 == null){
                                        WinLoseRecord newWlr1 = new WinLoseRecord();
                                        newWlr1.setOrderNo(o1.getOrderNo());
                                        newWlr1.setFaUserId(faUserId);
                                        newWlr1.setFaImg(faImg);
                                        newWlr1.setFaStatus(masterState);
                                        newWlr1.setFaUserImg(customerDao.queryById(faUserId).getHeadImg());
                                        newWlr1.setPkUserId(pkUserId);
                                        newWlr1.setPkImg(pkImg);
                                        newWlr1.setPkStatus(challengerState);
                                        newWlr1.setPkUserImg(customerDao.queryById(pkUserId).getHeadImg());
                                        winLoseRecordDao.save(newWlr1);
                                    }

                                    // 处理参与拼团后的利润分配
                                    ordersCopyService.handleCollageProfit(o1.getOrderPersonId(), p.getVoucher(), o1.getOrderNo());
                                }
                            }
                        }else{
                            // 挑战者赢了
                            if("1".equals(challengerState)){
                                Orders o = ordersDao.queryByGameId_1(pkGameId, pkUserId);
                                if(o != null){
                                    o.setDealStatus("1"); // 赢了修改订单为代发货
                                    ordersDao.update(o);

                                    mpg1.setStatus("1"); // 挑战者赢了 团为成功
                                    modeProductGameDao.update(mpg1);

                                    mpg.setStatus("1"); // 发起者的团也为成功 准备退款
                                    modeProductGameDao.update(mpg);

                                    Product product = productDao.queryById(o.getProductId());

                                    // 赢的人发货

                                    Account acc = accountDao.queryAccountByUserId(o.getOrderPersonId());
                                    // 送3个极乐值
                                    acc.setBliss(acc.getBliss() + 3);
                                    // 送等额的积分
                                    int give = (int)Math.round(o.getPayAmount().doubleValue());
                                    acc.setIntegral(acc.getIntegral() + give);
                                    // 拼中也送红包余额
                                    acc.setVoucherBalance(acc.getVoucherBalance().add(product.getVoucher1()));
                                    accountDao.update(acc);

                                    AccountRecord ar3 = new AccountRecord();
                                    ar3.setIntoUserId(o.getOrderPersonId());
                                    ar3.setOrderNo(o.getOrderNo());
                                    ar3.setType("2");
                                    ar3.setSign("1");
                                    ar3.setUpdateTime(new Date());
                                    ar3.setAmount(new BigDecimal(3));
                                    ar3.setNowAmount(new BigDecimal(acc.getBliss()));
                                    ar3.setInfo(customerDao.queryById(o.getOrderPersonId()).getAgentCode() + "参团成功! PK赢了获得极乐值：" + 3);
                                    accountRecordDao.save(ar3);

                                    AccountRecord ar3_1 = new AccountRecord();
                                    ar3_1.setIntoUserId(o.getOrderPersonId());
                                    ar3_1.setOrderNo(o.getOrderNo());
                                    ar3_1.setType("1");
                                    ar3_1.setSign("1");
                                    ar3_1.setUpdateTime(new Date());
                                    ar3_1.setAmount(new BigDecimal(give));
                                    ar3_1.setNowAmount(new BigDecimal(acc.getIntegral()));
                                    ar3_1.setInfo(customerDao.queryById(o.getOrderPersonId()).getAgentCode() + "参团成功! PK赢了获得积分：" + give);
                                    accountRecordDao.save(ar3_1);

                                    AccountRecord ar3_2 = new AccountRecord();
                                    ar3_2.setIntoUserId(o.getOrderPersonId());
                                    ar3_2.setUpdateTime(new Date());
                                    ar3_2.setType("0");
                                    ar3_2.setAmount(product.getVoucher1());
                                    ar3_2.setNowAmount(acc.getVoucherBalance());
                                    ar3_2.setSign("1");
                                    ar3_2.setOrderNo(o.getOrderNo());
                                    ar3_2.setInfo(customerDao.queryById(o.getOrderPersonId()).getAgentCode() + "参团成功! PK赢了获得红包：" + product.getVoucher1());
                                    accountRecordDao.save(ar3_2);

                                    // 存储输赢记录
                                    WinLoseRecord wlr = winLoseRecordDao.queryByOrderNo(o.getOrderNo());
                                    if(wlr == null){
                                        WinLoseRecord newWlr = new WinLoseRecord();
                                        newWlr.setOrderNo(o.getOrderNo());
                                        newWlr.setFaUserId(faUserId);
                                        newWlr.setFaImg(faImg);
                                        newWlr.setFaStatus(masterState);
                                        newWlr.setFaUserImg(customerDao.queryById(faUserId).getHeadImg());
                                        newWlr.setPkUserId(pkUserId);
                                        newWlr.setPkImg(pkImg);
                                        newWlr.setPkStatus(challengerState);
                                        newWlr.setPkUserImg(customerDao.queryById(pkUserId).getHeadImg());
                                        winLoseRecordDao.save(newWlr);
                                    }

                                    // 处理参与拼团后的利润分配
                                    ordersCopyService.handleCollageProfit(o.getOrderPersonId(), product.getVoucher1(), o.getOrderNo());

                                    // 输的人拿余额 退款 走人
                                    Orders o1 = ordersDao.queryByGameId(faGameId, faUserId);
                                    if(o1 != null){
                                        o1.setDealStatus("4"); // 交易关闭
                                        o1.setRefundStatus("2"); // 退款成功
                                        o1.setPayStatus("3"); // 已退款
                                        ordersDao.update(o1);

                                        Product p = productDao.queryById(o1.getProductId());

                                        Account acc1 = accountDao.queryAccountByUserId(o1.getOrderPersonId());
                                        acc1.setVoucherBalance(acc1.getVoucherBalance().add(o1.getPayAmount()));
                                        acc1.setVoucherBalance(acc1.getVoucherBalance().add(p.getVoucher()));
                                        accountDao.update(acc1);

                                        AccountRecord ar1_1 = new AccountRecord();
                                        ar1_1.setIntoUserId(o1.getOrderPersonId());
                                        ar1_1.setUpdateTime(new Date());
                                        ar1_1.setType("0");
                                        ar1_1.setAmount(o1.getPayAmount());
                                        ar1_1.setNowAmount(acc1.getVoucherBalance());
                                        ar1_1.setSign("1");
                                        ar1_1.setOrderNo(o1.getOrderNo());
                                        ar1_1.setInfo(customerDao.queryById(o1.getOrderPersonId()).getAgentCode() + "参团成功! PK输了,支付金额退回至余额：" + o1.getPayAmount());
                                        accountRecordDao.save(ar1_1);

                                        AccountRecord ar1_2 = new AccountRecord();
                                        ar1_2.setIntoUserId(o1.getOrderPersonId());
                                        ar1_2.setUpdateTime(new Date());
                                        ar1_2.setType("0");
                                        ar1_2.setAmount(p.getVoucher());
                                        ar1_2.setNowAmount(acc1.getVoucherBalance());
                                        ar1_2.setSign("1");
                                        ar1_2.setOrderNo(o1.getOrderNo());
                                        ar1_2.setInfo(customerDao.queryById(o1.getOrderPersonId()).getAgentCode() + "参团成功! PK输了,送您红包：" + p.getVoucher());
                                        accountRecordDao.save(ar1_2);

                                        BigDecimal couponAmount = null;
                                        if(o1.getCouponAmount() == null){
                                            couponAmount = new BigDecimal(0);
                                        }else{
                                            couponAmount = o1.getCouponAmount();
                                        }
                                        if(couponAmount.doubleValue() > 0){
                                            UserCoupon uc = userCouponDao.queryByUserIdAndCouponId(o1.getOrderPersonId(), 1); // 拼团券
                                            if(uc != null){
                                                int couponQuantity = (int) (couponAmount.doubleValue() / 9.9);
                                                uc.setQuantity(uc.getQuantity() + couponQuantity);
                                                userCouponDao.update(uc);

                                                AccountRecord ar2 = new AccountRecord();
                                                ar2.setIntoUserId(o1.getOrderPersonId());
                                                ar2.setUpdateTime(new Date());
                                                ar2.setType("5"); // 拼团券
                                                ar2.setAmount(new BigDecimal(couponQuantity));
                                                ar2.setNowAmount(new BigDecimal(uc.getQuantity()));
                                                ar2.setSign("1");
                                                ar2.setOrderNo(o1.getOrderNo());
                                                ar2.setInfo(customerDao.queryById(o1.getOrderPersonId()).getAgentCode() + "参团成功! 未抽中,拼团券退回：" + couponQuantity);
                                                accountRecordDao.save(ar2);
                                            }
                                        }

                                        // 存储输赢记录
                                        WinLoseRecord wlr1 = winLoseRecordDao.queryByOrderNo(o1.getOrderNo());
                                        if(wlr1 == null){
                                            WinLoseRecord newWlr1 = new WinLoseRecord();
                                            newWlr1.setOrderNo(o1.getOrderNo());
                                            newWlr1.setFaUserId(faUserId);
                                            newWlr1.setFaImg(faImg);
                                            newWlr1.setFaStatus(masterState);
                                            newWlr1.setFaUserImg(customerDao.queryById(faUserId).getHeadImg());
                                            newWlr1.setPkUserId(pkUserId);
                                            newWlr1.setPkImg(pkImg);
                                            newWlr1.setPkStatus(challengerState);
                                            newWlr1.setPkUserImg(customerDao.queryById(pkUserId).getHeadImg());
                                            winLoseRecordDao.save(newWlr1);
                                        }

                                        // 处理参与拼团后的利润分配
                                        ordersCopyService.handleCollageProfit(o1.getOrderPersonId(), p.getVoucher(), o1.getOrderNo());
                                    }
                                }
                            }
                        }
                    }
                }
            }
        }

        return ResponseServer.success();
    }


    /**
     * 加载拼团模式下的产品详情数据
     * @param productId
     * @return
     */
    @GetMapping("/getCollageModeProductDetailsData")
    public ResponseServer getCollageModeProductDetailsData(Integer productId){
        ProductVO vo = productDao.queryProductById(productId);
        if(vo.getBannerImg().length() > 0){
            String[] strings = vo.getBannerImg().split(";");
            List list = new ArrayList();
            for(int i = 0; i < strings.length; i++){
                list.add(strings[i]);
            }
            vo.setBannerImgList(list);
        }
        if(vo.getDetailsImg().length() > 0){
            String[] strings1 = vo.getDetailsImg().split(";");
            List list1 = new ArrayList();
            for(int y = 0; y < strings1.length; y++){
                list1.add(strings1[y]);
            }
            vo.setDetailsImgList(list1);
        }
        vo.setQuantity(1);

        List<SkuSVO> skuSVOList = new ArrayList<>();

        SkuSelected skuSelected = skuSelectedDao.querySkuSelectedByProductId(productId);
        int index = 0;
        if(skuSelected.getSpecAttribute().contains(",")){
            String[] strings = skuSelected.getSpecAttribute().split(",");
            for(int u = 0 ; u < strings.length; u++){
                String str = strings[u];

                SkuSVO skuSVO = new SkuSVO();
                skuSVO.setId(index);

                String[] strings1 = str.split("\\+");
                String specId = strings1[0];

                skuSVO.setProductId(productId);
                skuSVO.setSpecId(Integer.parseInt(specId));
                skuSVO.setSpecName(specAttributeDao.queryById(Integer.parseInt(specId)).getSpecName());

                List<SkuAVO> list = new ArrayList();

                String attIds = strings1[1];
                if(attIds.contains("_")){
                    String[] strings2 = attIds.split("_");
                    for(int p = 0; p < strings2.length; p++){
                        String attId = strings2[p];

                        SkuAVO skuAVO = new SkuAVO();
                        skuAVO.setArrId(Integer.parseInt(attId));
                        skuAVO.setAttName(specAttributeDao.queryById(Integer.parseInt(attId)).getAttributeName());
                        list.add(skuAVO);
                    }
                }else{
                    SkuAVO skuAVO = new SkuAVO();
                    skuAVO.setArrId(Integer.parseInt(attIds));
                    skuAVO.setAttName(specAttributeDao.queryById(Integer.parseInt(attIds)).getAttributeName());
                    list.add(skuAVO);
                }
                skuSVO.setSkuAVOList(list);

                skuSVOList.add(skuSVO);

                index++;
            }
        }else{
            String str = skuSelected.getSpecAttribute();

            SkuSVO skuSVO = new SkuSVO();
            skuSVO.setId(index);

            String[] strings1 = str.split("\\+");
            String specId = strings1[0];

            skuSVO.setProductId(productId);
            skuSVO.setSpecId(Integer.parseInt(specId));
            skuSVO.setSpecName(specAttributeDao.queryById(Integer.parseInt(specId)).getSpecName());

            List<SkuAVO> list = new ArrayList();

            String attIds = strings1[1];
            if(attIds.contains("_")){
                String[] strings2 = attIds.split("_");
                for(int p = 0; p < strings2.length; p++){
                    String attId = strings2[p];

                    SkuAVO skuAVO = new SkuAVO();
                    skuAVO.setArrId(Integer.parseInt(attId));
                    skuAVO.setAttName(specAttributeDao.queryById(Integer.parseInt(attId)).getAttributeName());
                    list.add(skuAVO);
                }
            }else{
                SkuAVO skuAVO = new SkuAVO();
                skuAVO.setArrId(Integer.parseInt(attIds));
                skuAVO.setAttName(specAttributeDao.queryById(Integer.parseInt(attIds)).getAttributeName());
                list.add(skuAVO);
            }
            skuSVO.setSkuAVOList(list);

            skuSVOList.add(skuSVO);
        }

        vo.setSkuSVOList(skuSVOList);

        List<SkuRelation> skuRelationList = skuRelationDao.queryByProductId(productId);
        vo.setSkuRVOList(skuRelationList);

        ModeProduct modeProduct = modeProductDao.queryByProductIdByStatus(productId);
        if(modeProduct != null){
            List<CollageUser> collageUserList = collageUserDao.queryByModeProductId(modeProduct.getId());
            int rowSize = collageUserList.size();
            if(modeProduct.getModeId() == 2){
                vo.setJoinPeople(rowSize);
                vo.setSign("1");
                if(rowSize > 0){
                    if(rowSize > 9){
                        List<String> stringList = new ArrayList<>();
                        List<CollageUser> collageUserList1 = collageUserList.subList(0, 9);
                        for(CollageUser cu : collageUserList1){
                            stringList.add(customerDao.queryById(cu.getUserId()).getHeadImg());
                        }
                        vo.setStringList(stringList);
                    }else{
                        List<String> stringList = new ArrayList<>();
                        for(CollageUser cu : collageUserList){
                            stringList.add(customerDao.queryById(cu.getUserId()).getHeadImg());
                        }
                        vo.setStringList(stringList);
                    }
                }
            }else{
                vo.setSign("0");
                vo.setSurplusPeople(collageModeDao.queryById(modeProduct.getModeId()).getPeopleQuantity() - rowSize);
                if(rowSize > 0){
                    List<String> stringList = new ArrayList<>();
                    for(CollageUser cu : collageUserList){
                        stringList.add(customerDao.queryById(cu.getUserId()).getHeadImg());
                    }
                    vo.setStringList(stringList);
                }
            }
        }else{
            CollageMode cm = collageModeDao.queryById(vo.getCollageModeId());
            if(vo.getCollageModeId() == 2){
                vo.setSurplusPeople(cm.getPeopleQuantity());
            }else if(vo.getCollageModeId() == 3){
                vo.setSurplusPeople(cm.getPeopleQuantity());
            }else if(vo.getCollageModeId() == 4){
                vo.setSurplusPeople(cm.getPeopleQuantity());
            }else if(vo.getCollageModeId() == 20){
                vo.setSurplusPeople(cm.getPeopleQuantity());
            }
        }
        if(vo.getJoinPeople() == null){
            vo.setJoinPeople(0);
        }
        return ResponseServer.success(vo);
    }


    /**
     * 购买拼团游戏产品，微信支付
     * @param request
     * @param productId
     * @param openId
     * @param consigneeName
     * @param fullAddress
     * @param consigneePhone
     * @param userId
     * @param freight
     * @return
     */
    @PostMapping("/collage/game/pay")
    public ResponseServer collageGamePay(HttpServletRequest request, @RequestParam(required = false) Integer productId,
                                         @RequestParam(required = false) String openId,
                                         @RequestParam(required = false) String consigneeName,
                                         @RequestParam(required = false) String fullAddress,
                                         @RequestParam(required = false) String consigneePhone,
                                         @RequestParam(required = false) Integer userId,
                                         @RequestParam(required = false) BigDecimal freight,
                                         @RequestParam(required = false) BigDecimal couponPrice,
                                         @RequestParam(required = false) Integer couponQuantity,
                                         @RequestParam(required = false) Integer skuId,
                                         @RequestParam(required = false) Integer couponId,
                                         @RequestParam(required = false) String field,
                                         @RequestParam(required = false) String modeProductGameId) throws Exception {

        Map<String, String> maps = new HashMap<>();

        Product product = productDao.queryById(productId);
        if(product == null){
            maps.put("prepayId", "");
            maps.put("msg", "支付失败,产品信息错误");
            return ResponseServer.success(maps);
        }

        CollageMode collageMode = collageModeDao.queryById(product.getCollageModeId());
        if(collageMode == null){
            maps.put("prepayId", "");
            maps.put("msg", "支付失败,拼团模式错误");
            return ResponseServer.success(maps);
        }

        Customer customer = customerDao.queryById(userId);
        if(customer == null){
            maps.put("prepayId", "");
            maps.put("msg", "支付失败,用户信息错误");
            return ResponseServer.success(maps);
        }

        if("new".equals(field)){
            // 判断自己的团是否已经买这个产品了并且是进行中的
            ModeProductUserDTO dto = modeProductGameDao.queryByIds(product.getCollageModeId(), product.getId(), customer.getId());
            if(dto != null){
                maps.put("prepayId", "");
                maps.put("msg", "当前产品房间已创建，请勿重复创建");
                return ResponseServer.success(maps);
            }
        }else if("old".equals(field)){
            ModeProductUserDTO dto = modeProductGameDao.queryByIds_1(product.getCollageModeId(), Integer.parseInt(modeProductGameId));
            if(dto != null){
                maps.put("prepayId", "");
                maps.put("msg", "当前房间已被别人抢先一步,正在PK中,请选择其他房间参与");
                return ResponseServer.success(maps);
            }
        }

        BigDecimal totalPrice; // 需要支付的金额
        // 商户订单号
        String outTradeNo = "BEE" + Units.getOrderIdByTime().replaceAll("-", "");
        // 交易号
        String tradeNo = "JYH" + Units.getOrderIdByTime().replaceAll("-", "");
        if (freight == null) {
            freight = BigDecimal.valueOf(0.0);
        }
        if(couponPrice == null){
            couponPrice = BigDecimal.valueOf(0.0);
        }
        SkuRelation sku = skuRelationDao.queryById(skuId);
        BigDecimal totalAmount = sku.getRetailPrice(); // 产品总金额
        totalPrice = sku.getRetailPrice().add(freight).subtract(couponPrice);
        Map<String, String> map;
        if (totalPrice.doubleValue() > 0) {
            Map<String, Object> wxPay = new HashMap<>();
            wxPay.put("totalPrice", totalPrice.doubleValue());
            wxPay.put("outTradeNo", outTradeNo);
            wxPay.put("openId", openId);
            wxPay.put("notifyUrl", Constants.notify_url_collage_game);
            wxPay.put("wxPayAppId", Constants.wxAppId);
            wxPay.put("tradeType", Constants.trade_type);
            String paramBuffer = CreateUnifiedOrder.UnifiedOrder(request, wxPay);
            map = Units.doXMLParse(HttpRequestUtil.sendPost(Constants.pay_url, new String(paramBuffer.getBytes(), "UTF-8")));
            if (map != null) {

                // 创建团
                ModeProductGame mpg = new ModeProductGame();
                if("new".equals(field)){
                    mpg.setIsRoom("1");
                }else if("old".equals(field)){
                    mpg.setParentId(Integer.parseInt(modeProductGameId));
                }
                mpg.setModeId(product.getCollageModeId());
                mpg.setStatus("0");
                mpg.setProductId(product.getId());
                mpg.setUpdateTime(new Date());
                modeProductGameDao.save(mpg);

                CollageUserGame cug = new CollageUserGame();
                cug.setModeProductGameId(mpg.getId());
                cug.setUserId(userId);
                cug.setUpdateTime(new Date());
                collageUserGameDao.save(cug);

                // 创建订单
                Orders orders = new Orders();
                orders.setOrderNo(outTradeNo);
                orders.setTradeNo(tradeNo);
                orders.setTotalAmount(totalAmount);
                orders.setPayAmount(totalPrice);
                orders.setCouponAmount(couponPrice);
                orders.setFreight(freight);
                orders.setPayStatus("0");
                orders.setPayType("0");
                orders.setDealStatus("0");
                orders.setRefundStatus("0");
                orders.setCollageModeId(product.getCollageModeId());
                orders.setModeName(collageMode.getName());
                orders.setProductId(product.getId());
                orders.setModeProductId(mpg.getId());
                orders.setOrderPersonId(userId);
                orders.setConsigneeName(consigneeName);
                orders.setConsigneePhone(consigneePhone);
                orders.setAddress(fullAddress);
                orders.setPrepayId(map.get("prepay_id"));
                orders.setUpdateTime(new Date());
                orders.setIsDel("0");
                orders.setIsRun("0");
                orders.setLastCollage("0");
                orders.setRemarks("无");
                if("new".equals(field)){
                    orders.setInitiator("1");
                }else if("old".equals(field)){
                    orders.setInitiator("0");
                }
                ordersDao.save(orders);

                // 订单详情
                OrderDetails od = new OrderDetails();
                od.setOrderNo(orders.getOrderNo());
                od.setTradeNo(orders.getTradeNo());
                od.setStoreShopId(product.getStoreShopId());
                od.setStoreShopName(storeShopDao.queryById(product.getStoreShopId()).getName());
                od.setClassifyId(product.getClassifyId());
                od.setClassifyName(classifyDao.queryById(product.getClassifyId()).getName());
                od.setProductId(product.getId());
                od.setProductType(product.getType());
                od.setProductImg(product.getImg());
                od.setProductName(product.getName());
                od.setProductCode(product.getProductCode());
                od.setCostPrice(sku.getCostPrice());
                od.setRelationId(sku.getId());
                if(sku.getGroupRelation().contains(",")){
                    String[] strings = sku.getGroupRelation().split(",");
                    String str = "";
                    for(int u = 0; u < strings.length; u++){
                        str += specAttributeDao.queryById(Integer.parseInt(strings[u])).getAttributeName() + "，";
                    }
                    od.setSpecAttributeName(str.substring(0, str.length()-1));
                }else{
                    od.setSpecAttributeName(specAttributeDao.queryById(Integer.parseInt(sku.getGroupRelation())).getAttributeName());
                }
                od.setQuantity(1);
                od.setUnitPrice(sku.getRetailPrice());
                od.setUpdateTime(new Date());
                orderDetailsDao.save(od);

                maps.put("prepayId", map.get("prepay_id"));
                maps.put("outTradeNo", outTradeNo);
                return ResponseServer.success(maps);
            }
        }
        maps.put("prepayId", "");
        maps.put("msg", "支付失败,请重试");
        return ResponseServer.success(maps);
    }


    /**
     * 拼团游戏支付成功后回调
     * @param request
     * @param response
     */
    @PostMapping("/notify_url_collage_game")
    public void collageGamePayCallback(HttpServletRequest request, HttpServletResponse response) {
        System.err.println("微信回调接口方法 start ----------------------------");
        String inputLine = "";
        String notityXml = "";
        try {
            while ((inputLine = request.getReader().readLine()) != null) {
                notityXml += inputLine;
            }
            // 关闭流
            request.getReader().close();
            System.err.println("小程序商城支付回调：" + notityXml);
            // 解析成Map
            Map<String, String> map = Units.doXMLParse(notityXml);
            System.err.println(map);
            // 判断 支付是否成功
            if ("SUCCESS".equals(map.get("result_code"))) {
                System.err.println("微信回调返回是否支付成功：是");
                // 获得 返回的商户订单号
                String outTradeNo = map.get("out_trade_no");

                Orders orders = ordersDao.queryByOrderNo(outTradeNo);
                orders.setPayStatus("1");
                orders.setDealStatus("6");
                ordersDao.update(orders);

                Product product = productDao.queryById(orders.getProductId());
                product.setSales(product.getSales() + 1); // 添加销量
                productDao.update(product);

                // 查看是否需要扣除拼团券
                BigDecimal couponAmount = null;
                if(orders.getCouponAmount() == null){
                    couponAmount = new BigDecimal(0);
                }else{
                    couponAmount = orders.getCouponAmount();
                }
                if(couponAmount.doubleValue() > 0){
                    UserCoupon uc = userCouponDao.queryByUserIdAndCouponId(orders.getOrderPersonId(), 1); // 拼团券
                    if(uc != null){
                        int couponQuantity = (int) (couponAmount.doubleValue() / 9.9);
                        uc.setQuantity(uc.getQuantity() - couponQuantity);
                        userCouponDao.update(uc);

                        AccountRecord ar2 = new AccountRecord();
                        ar2.setOutUserId(orders.getOrderPersonId());
                        ar2.setUpdateTime(new Date());
                        ar2.setType("5"); // 拼团券
                        ar2.setAmount(new BigDecimal(couponQuantity));
                        ar2.setNowAmount(new BigDecimal(uc.getQuantity()));
                        ar2.setSign("2");
                        ar2.setOrderNo(outTradeNo);
                        ar2.setInfo(customerDao.queryById(orders.getOrderPersonId()).getAgentCode() + "参团成功! 消费拼团券：" + couponQuantity);
                        accountRecordDao.save(ar2);
                    }
                }

                Customer customer = customerDao.queryById(orders.getOrderPersonId());

                // 处理等级
                handleCollageLevel(customer, outTradeNo);

                // 封装 返回值
                StringBuffer buffer = new StringBuffer();
                buffer.append("<xml>");
                buffer.append("<return_code>SUCCESS</return_code>");
                buffer.append("<return_msg>OK</return_msg>");
                buffer.append("</xml>");
                // 给微信服务器返回 成功标示 否则会一直询问服务器是否回调成功
                PrintWriter writer = response.getWriter();
                // 返回
                writer.print(buffer.toString());
            }
        } catch (IOException e) {
            e.printStackTrace();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }


    /**
     * 购买拼团游戏产品，余额支付
     * @param productId
     * @param openId
     * @param consigneeName
     * @param fullAddress
     * @param consigneePhone
     * @param userId
     * @param freight
     * @param couponPrice
     * @param couponQuantity
     * @param skuId
     * @param couponId
     * @param field
     * @param modeProductGameId
     * @return
     */
    @PostMapping("/collage/game/pay/voucher")
    public ResponseServer collageGamePayVoucher(@RequestParam(required = false) Integer productId,
                                            @RequestParam(required = false) String openId,
                                            @RequestParam(required = false) String consigneeName,
                                            @RequestParam(required = false) String fullAddress,
                                            @RequestParam(required = false) String consigneePhone,
                                            @RequestParam(required = false) Integer userId,
                                            @RequestParam(required = false) BigDecimal freight,
                                            @RequestParam(required = false) BigDecimal couponPrice,
                                            @RequestParam(required = false) Integer couponQuantity,
                                            @RequestParam(required = false) Integer skuId,
                                            @RequestParam(required = false) Integer couponId,
                                                @RequestParam(required = false) String field,
                                                @RequestParam(required = false) String modeProductGameId) {
        String strs = "";
        // 创建房间
        if ("new".equals(field)) {

            Product product = productDao.queryById(productId);
            if(product == null){
                return ResponseServer.error("支付失败，拼团模式信息不正确，请联系管理员");
            }

            CollageMode collageMode = collageModeDao.queryById(product.getCollageModeId());
            if(collageMode == null){
                return ResponseServer.error("支付失败，拼团信息不正确，请联系管理员");
            }

            Customer customer = customerDao.queryById(userId);
            if(customer == null){
                return ResponseServer.error("支付失败，用户信息不正确，请联系管理员");
            }

            // 判断自己的团是否已经买这个产品了并且是进行中的
            ModeProductUserDTO dto = modeProductGameDao.queryByIds(product.getCollageModeId(), product.getId(), customer.getId());
            if(dto != null){
                return ResponseServer.error("当前产品房间已创建，请勿重复创建");
            }

            Account account = accountDao.queryAccountByUserId(userId);
            if(account.getBliss() < product.getBliss()) {
                return ResponseServer.error("参团失败,极乐值不足");
            }

            BigDecimal totalPrice; // 实际支付的钱
            // 商户订单号
            String outTradeNo = "BEE" + Units.getOrderIdByTime().replaceAll("-", "");
            // 交易号
            String tradeNo = "JYH" + Units.getOrderIdByTime().replaceAll("-", "");
            if (freight == null) {
                freight = BigDecimal.valueOf(0.0);
            }
            if (couponPrice == null) {
                couponPrice = BigDecimal.valueOf(0.0);
            }
            SkuRelation sku = skuRelationDao.queryById(skuId);
            if(sku == null){
                return ResponseServer.error("支付失败，产品SKU信息不正确，请联系管理员");
            }
            BigDecimal totalAmount = sku.getRetailPrice(); // 产品总金额
            totalPrice = sku.getRetailPrice().add(freight).subtract(couponPrice);
            if(account.getVoucherBalance().doubleValue() < totalPrice.doubleValue()){
                return ResponseServer.error("支付失败,余额不足!!!");
            }
            account.setVoucherBalance(account.getVoucherBalance().subtract(totalPrice));
            if(product.getBliss() > 0){
                account.setBliss(account.getBliss() - product.getBliss());
            }
            accountDao.update(account);

            AccountRecord ar = new AccountRecord();
            ar.setOutUserId(userId);
            ar.setUpdateTime(new Date());
            ar.setType("0");
            ar.setAmount(totalPrice);
            ar.setNowAmount(account.getVoucherBalance());
            ar.setSign("2");
            ar.setOrderNo(outTradeNo);
            ar.setInfo(customer.getAgentCode() + "参团成功! 消费余额：" + totalPrice);
            accountRecordDao.save(ar);

            if(product.getBliss() > 0) {
                AccountRecord ar1 = new AccountRecord();
                ar1.setOutUserId(userId);
                ar1.setUpdateTime(new Date());
                ar1.setType("2");
                ar1.setAmount(new BigDecimal(product.getBliss()));
                ar1.setNowAmount(new BigDecimal(account.getBliss()));
                ar1.setSign("2");
                ar1.setOrderNo(outTradeNo);
                ar1.setInfo(customer.getAgentCode() + "参团成功! 消耗极乐值：" + product.getBliss());
                accountRecordDao.save(ar1);
            }

            int uu = (int) (couponPrice.doubleValue() / 9.9);
            if(uu > 0){
                UserCoupon uc = userCouponDao.queryByUserIdAndCouponId(userId, couponId);
                if(uc != null){
                    uc.setQuantity(uc.getQuantity() - uu);
                    userCouponDao.update(uc);

                    AccountRecord ar2 = new AccountRecord();
                    ar2.setOutUserId(userId);
                    ar2.setUpdateTime(new Date());
                    ar2.setType("5"); // 拼团券
                    ar2.setAmount(new BigDecimal(uu));
                    ar2.setNowAmount(new BigDecimal(uc.getQuantity()));
                    ar2.setSign("2");
                    ar2.setOrderNo(outTradeNo);
                    ar2.setInfo(customer.getAgentCode() + "参团成功! 消费拼团券：" + uu);
                    accountRecordDao.save(ar2);
                }
            }

            // 创建团
            ModeProductGame mpg = new ModeProductGame();
            if("new".equals(field)){
                mpg.setIsRoom("1");
            }else if("old".equals(field)){
                mpg.setParentId(Integer.parseInt(modeProductGameId));
            }
            mpg.setModeId(product.getCollageModeId());
            mpg.setStatus("0");
            mpg.setProductId(product.getId());
            mpg.setUpdateTime(new Date());
            modeProductGameDao.save(mpg);

            CollageUserGame cug = new CollageUserGame();
            cug.setModeProductGameId(mpg.getId());
            cug.setUserId(userId);
            cug.setUpdateTime(new Date());
            collageUserGameDao.save(cug);

            // 创建订单
            Orders orders = new Orders();
            orders.setOrderNo(outTradeNo);
            orders.setTradeNo(tradeNo);
            orders.setTotalAmount(totalAmount);
            orders.setPayAmount(totalPrice);
            orders.setCouponAmount(couponPrice);
            orders.setFreight(freight);
            orders.setPayStatus("1");
            orders.setPayType("1");
            orders.setDealStatus("6"); // 等待开团
            orders.setRefundStatus("0");
            orders.setPrepayId("");
            orders.setCollageModeId(product.getCollageModeId());
            orders.setModeName(collageMode.getName());
            orders.setProductId(product.getId());
            orders.setModeProductId(mpg.getId());
            orders.setOrderPersonId(userId);
            orders.setConsigneeName(consigneeName);
            orders.setConsigneePhone(consigneePhone);
            orders.setAddress(fullAddress);
            orders.setPrepayId("");
            orders.setUpdateTime(new Date());
            orders.setIsDel("0");
            orders.setIsRun("0");
            orders.setLastCollage("0");
            orders.setRemarks("无");
            orders.setInitiator("1"); // 创建者
            ordersDao.save(orders);

            // 订单详情
            OrderDetails od = new OrderDetails();
            od.setOrderNo(orders.getOrderNo());
            od.setTradeNo(orders.getTradeNo());
            od.setStoreShopId(product.getStoreShopId());
            od.setStoreShopName(storeShopDao.queryById(product.getStoreShopId()).getName());
            od.setClassifyId(product.getClassifyId());
            od.setClassifyName(classifyDao.queryById(product.getClassifyId()).getName());
            od.setProductId(product.getId());
            od.setProductType(product.getType());
            od.setProductImg(product.getImg());
            od.setProductName(product.getName());
            od.setProductCode(product.getProductCode());
            od.setCostPrice(sku.getCostPrice());
            od.setRelationId(sku.getId());
            if(sku.getGroupRelation().contains(",")){
                String[] strings = sku.getGroupRelation().split(",");
                String str = "";
                for(int u = 0; u < strings.length; u++){
                    str += specAttributeDao.queryById(Integer.parseInt(strings[u])).getAttributeName() + "，";
                }
                od.setSpecAttributeName(str.substring(0, str.length()-1));
            }else{
                od.setSpecAttributeName(specAttributeDao.queryById(Integer.parseInt(sku.getGroupRelation())).getAttributeName());
            }
            od.setQuantity(1);
            od.setUnitPrice(sku.getRetailPrice());
            od.setUpdateTime(new Date());
            orderDetailsDao.save(od);

            // 添加销量
            product.setSales(product.getSales() + 1);
            productDao.update(product);

            // 处理等级
            handleCollageLevel(customer, outTradeNo);

            return ResponseServer.success("余额支付成功!!!", orders);
        }

        // PK
        else if ("old".equals(field)) {
            // Lock lock = new ReentrantLock(); // 创建一个锁对象
            // lock.lock();
            boolean temp = false;
            Orders orders = null;
            try {
                Map map = judgeCollageOrders(productId, openId, consigneeName, fullAddress, consigneePhone, userId, freight, couponPrice, couponQuantity, skuId, couponId, field, modeProductGameId);
                if("1".equals(map.get("temp").toString())){
                    temp = true;
                    orders = (Orders) map.get("orders");
                }
                strs = map.get("str").toString();
            } catch (Exception e) {
                e.printStackTrace();
            } finally {
                // lock.unlock();
            }
            if (temp) {
                return ResponseServer.success(strs, orders);
            }
            return ResponseServer.error(strs);
        }

        return ResponseServer.error(strs);

    }


    public synchronized Map judgeCollageOrders(Integer productId, String openId, String consigneeName, String fullAddress, String consigneePhone, Integer userId, BigDecimal freight,
                                  BigDecimal couponPrice, Integer couponQuantity, Integer skuId, Integer couponId, String field, String modeProductGameId){
        Map map = new HashMap();
        Product product = productDao.queryById(productId);
        if(product == null){
            map.put("temp", "2");
            map.put("str", "支付失败，拼团模式信息不正确，请联系管理员");
            return map;
        }

        CollageMode collageMode = collageModeDao.queryById(product.getCollageModeId());
        if(collageMode == null){
            map.put("temp", "2");
            map.put("str", "支付失败，拼团信息不正确，请联系管理员");
            return map;
        }

        Customer customer = customerDao.queryById(userId);
        if(customer == null){
            map.put("temp", "2");
            map.put("str", "支付失败，用户信息不正确，请联系管理员");
            return map;
        }

        // 判断自己的团是否已经买这个产品了并且是进行中的
        ModeProductUserDTO dto = modeProductGameDao.queryByIds_1(product.getCollageModeId(), Integer.parseInt(modeProductGameId));
        if(dto != null){
            map.put("temp", "2");
            map.put("str", "当前房间已被别人抢先一步,正在PK中,请选择其他房间参与");
            return map;
        }

        Account account = accountDao.queryAccountByUserId(userId);
        if(account.getBliss() < product.getBliss()) {
            map.put("temp", "2");
            map.put("str", "参团失败,极乐值不足");
            return map;
        }

        BigDecimal totalPrice; // 实际支付的钱
        // 商户订单号
        String outTradeNo = "BEE" + Units.getOrderIdByTime().replaceAll("-", "");
        // 交易号
        String tradeNo = "JYH" + Units.getOrderIdByTime().replaceAll("-", "");
        if (freight == null) {
            freight = BigDecimal.valueOf(0.0);
        }
        if (couponPrice == null) {
            couponPrice = BigDecimal.valueOf(0.0);
        }
        SkuRelation sku = skuRelationDao.queryById(skuId);
        if(sku == null){
            map.put("temp", "2");
            map.put("str", "支付失败，产品SKU信息不正确，请联系管理员");
            return map;
        }
        BigDecimal totalAmount = sku.getRetailPrice(); // 产品总金额
        totalPrice = sku.getRetailPrice().add(freight).subtract(couponPrice);
        if(account.getVoucherBalance().doubleValue() < totalPrice.doubleValue()){
            map.put("temp", "2");
            map.put("str", "支付失败,余额不足");
            return map;
        }
        account.setVoucherBalance(account.getVoucherBalance().subtract(totalPrice));
        if(product.getBliss() > 0) {
            account.setBliss(account.getBliss() - product.getBliss());
        }
        accountDao.update(account);

        AccountRecord ar = new AccountRecord();
        ar.setOutUserId(userId);
        ar.setUpdateTime(new Date());
        ar.setType("0");
        ar.setAmount(totalPrice);
        ar.setNowAmount(account.getVoucherBalance());
        ar.setSign("2");
        ar.setOrderNo(outTradeNo);
        ar.setInfo(customer.getAgentCode() + "参团成功! 消费余额：" + totalPrice);
        accountRecordDao.save(ar);

        if(product.getBliss() > 0) {
            AccountRecord ar1 = new AccountRecord();
            ar1.setOutUserId(userId);
            ar1.setUpdateTime(new Date());
            ar1.setType("2");
            ar1.setAmount(new BigDecimal(product.getBliss()));
            ar1.setNowAmount(new BigDecimal(account.getBliss()));
            ar1.setSign("2");
            ar1.setOrderNo(outTradeNo);
            ar1.setInfo(customer.getAgentCode() + "参团成功! 消耗极乐值：" + product.getBliss());
            accountRecordDao.save(ar1);
        }

        int uu = (int) (couponPrice.doubleValue() / 9.9);
        if(uu > 0){
            UserCoupon uc = userCouponDao.queryByUserIdAndCouponId(userId, couponId);
            if(uc != null){
                uc.setQuantity(uc.getQuantity() - uu);
                userCouponDao.update(uc);

                AccountRecord ar2 = new AccountRecord();
                ar2.setOutUserId(userId);
                ar2.setUpdateTime(new Date());
                ar2.setType("5"); // 拼团券
                ar2.setAmount(new BigDecimal(uu));
                ar2.setNowAmount(new BigDecimal(uc.getQuantity()));
                ar2.setSign("2");
                ar2.setOrderNo(outTradeNo);
                ar2.setInfo(customer.getAgentCode() + "参团成功! 消费拼团券：" + uu);
                accountRecordDao.save(ar2);
            }
        }

        // 创建团
        ModeProductGame mpg = new ModeProductGame();
        if("new".equals(field)){
            mpg.setIsRoom("1");
        }else if("old".equals(field)){
            mpg.setParentId(Integer.parseInt(modeProductGameId));
        }
        mpg.setModeId(product.getCollageModeId());
        mpg.setStatus("0");
        mpg.setProductId(product.getId());
        mpg.setUpdateTime(new Date());
        modeProductGameDao.save(mpg);

        CollageUserGame cug = new CollageUserGame();
        cug.setModeProductGameId(mpg.getId());
        cug.setUserId(userId);
        cug.setUpdateTime(new Date());
        collageUserGameDao.save(cug);

        // 创建订单
        Orders orders = new Orders();
        orders.setOrderNo(outTradeNo);
        orders.setTradeNo(tradeNo);
        orders.setTotalAmount(totalAmount);
        orders.setPayAmount(totalPrice);
        orders.setCouponAmount(couponPrice);
        orders.setFreight(freight);
        orders.setPayStatus("1");
        orders.setPayType("1");
        orders.setDealStatus("6"); // 等待开团
        orders.setRefundStatus("0");
        orders.setPrepayId("");
        orders.setCollageModeId(product.getCollageModeId());
        orders.setModeName(collageMode.getName());
        orders.setProductId(product.getId());
        orders.setModeProductId(mpg.getId());
        orders.setOrderPersonId(userId);
        orders.setConsigneeName(consigneeName);
        orders.setConsigneePhone(consigneePhone);
        orders.setAddress(fullAddress);
        orders.setPrepayId("");
        orders.setUpdateTime(new Date());
        orders.setIsDel("0");
        orders.setIsRun("0");
        orders.setLastCollage("0");
        orders.setRemarks("无");
        orders.setInitiator("0"); // 挑战者
        ordersDao.save(orders);

        // 订单详情
        OrderDetails od = new OrderDetails();
        od.setOrderNo(orders.getOrderNo());
        od.setTradeNo(orders.getTradeNo());
        od.setStoreShopId(product.getStoreShopId());
        od.setStoreShopName(storeShopDao.queryById(product.getStoreShopId()).getName());
        od.setClassifyId(product.getClassifyId());
        od.setClassifyName(classifyDao.queryById(product.getClassifyId()).getName());
        od.setProductId(product.getId());
        od.setProductType(product.getType());
        od.setProductImg(product.getImg());
        od.setProductName(product.getName());
        od.setProductCode(product.getProductCode());
        od.setCostPrice(sku.getCostPrice());
        od.setRelationId(sku.getId());
        if(sku.getGroupRelation().contains(",")){
            String[] strings = sku.getGroupRelation().split(",");
            String str = "";
            for(int u = 0; u < strings.length; u++){
                str += specAttributeDao.queryById(Integer.parseInt(strings[u])).getAttributeName() + "，";
            }
            od.setSpecAttributeName(str.substring(0, str.length()-1));
        }else{
            od.setSpecAttributeName(specAttributeDao.queryById(Integer.parseInt(sku.getGroupRelation())).getAttributeName());
        }
        od.setQuantity(1);
        od.setUnitPrice(sku.getRetailPrice());
        od.setUpdateTime(new Date());
        orderDetailsDao.save(od);

        // 添加销量
        product.setSales(product.getSales() + 1);
        productDao.update(product);

        // 处理等级
        handleCollageLevel(customer, outTradeNo);

        map.put("temp", "1");
        map.put("str", "余额支付成功!!!");
        map.put("orders", orders);
        return map;
    }


    /**
     * 判断是否存在正在进行中的速度与激情
     * @return
     */
    @GetMapping("/judgeJoinCollageMode20")
    public ResponseServer judgeJoinCollageMode20(Integer userId){
        List<Orders> ordersList = ordersDao.queryByJudgeJoinCollageMode20(userId);
        if(ordersList.size() > 0){
            return ResponseServer.error("不能参与");
        }else{
            return ResponseServer.success("可以参与");
        }
    }


    /**
     * 购买拼团产品，余额支付
     * @param productId
     * @param openId
     * @param consigneeName
     * @param fullAddress
     * @param consigneePhone
     * @param userId
     * @param freight
     * @return
     */
    @PostMapping("/collage/pay/voucher")
    public ResponseServer collagePayVoucher(@RequestParam(required = false) Integer productId,
                                            @RequestParam(required = false) String openId,
                                            @RequestParam(required = false) String consigneeName,
                                            @RequestParam(required = false) String fullAddress,
                                            @RequestParam(required = false) String consigneePhone,
                                            @RequestParam(required = false) Integer userId,
                                            @RequestParam(required = false) BigDecimal freight,
                                            @RequestParam(required = false) BigDecimal couponPrice,
                                            @RequestParam(required = false) Integer couponQuantity,
                                            @RequestParam(required = false) Integer skuId,
                                            @RequestParam(required = false) boolean isSpellSelect,
                                            @RequestParam(required = false) Integer couponId) throws ParseException {

        System.err.println("-------------创建订单传递的参数：productId= " + productId);
        System.err.println("-------------创建订单传递的参数：openId= " + openId);
        System.err.println("-------------创建订单传递的参数：consigneeName= " + consigneeName);
        System.err.println("-------------创建订单传递的参数：fullAddress= " + fullAddress);
        System.err.println("-------------创建订单传递的参数：consigneePhone= " + consigneePhone);
        System.err.println("-------------创建订单传递的参数：userId= " + userId);
        System.err.println("-------------创建订单传递的参数：freight= " + freight);
        System.err.println("-------------创建订单传递的参数：couponPrice= " + couponPrice);
        System.err.println("-------------创建订单传递的参数：couponQuantity= " + couponQuantity);
        System.err.println("-------------创建订单传递的参数：skuId= " + skuId);
        System.err.println("-------------创建订单传递的参数：isSpellSelect= " + isSpellSelect);
        System.err.println("-------------创建订单传递的参数：couponId= " + couponId);

        Product product = productDao.queryById(productId);
        if(product == null){
            return ResponseServer.error("支付失败,产品信息错误，请联系管理员");
        }

        CollageMode collageMode = collageModeDao.queryById(product.getCollageModeId());
        if(collageMode == null){
            return ResponseServer.error("支付失败,拼团模式不正确，请联系管理员");
        }

        Customer customer = customerDao.queryById(userId);
        if(customer == null){
            return ResponseServer.error("支付失败,用户信息不正确，请重新授权");
        }

        Account account = accountDao.queryAccountByUserId(userId);
        if(account.getBliss() < product.getBliss()) {
            return ResponseServer.error("参团失败,极乐值不足");
        }

        BigDecimal totalPrice; // 实际支付的钱
        // 商户订单号
        String outTradeNo = "BEE" + Units.getOrderIdByTime().replaceAll("-", "");
        // 交易号
        String tradeNo = "JYH" + Units.getOrderIdByTime().replaceAll("-", "");
        if (freight == null) {
            freight = BigDecimal.valueOf(0.0);
        }
        if (couponPrice == null) {
            couponPrice = BigDecimal.valueOf(0.0);
        }
        SkuRelation sku = skuRelationDao.queryById(skuId);
        if(sku == null){
            return ResponseServer.error("支付失败,产品信息不正确，请联系管理员");
        }
        BigDecimal totalAmount = sku.getRetailPrice(); // 产品总金额
        totalPrice = sku.getRetailPrice().add(freight).subtract(couponPrice);
        if(account.getVoucherBalance().doubleValue() < totalPrice.doubleValue()){
            return ResponseServer.error("支付失败,余额不足");
        }
        account.setVoucherBalance(account.getVoucherBalance().subtract(totalPrice));
        if(product.getBliss() > 0) {
            account.setBliss(account.getBliss() - product.getBliss());
        }
        accountDao.update(account);

        AccountRecord ar = new AccountRecord();
        ar.setOutUserId(userId);
        ar.setUpdateTime(new Date());
        ar.setType("0");
        ar.setAmount(totalPrice);
        ar.setNowAmount(account.getVoucherBalance());
        ar.setSign("2");
        ar.setOrderNo(outTradeNo);
        ar.setInfo(customer.getAgentCode() + "参团成功! 消费余额：" + totalPrice);
        accountRecordDao.save(ar);

        if(product.getBliss() > 0) {
            AccountRecord ar1 = new AccountRecord();
            ar1.setOutUserId(userId);
            ar1.setUpdateTime(new Date());
            ar1.setType("2");
            ar1.setAmount(new BigDecimal(product.getBliss()));
            ar1.setNowAmount(new BigDecimal(account.getBliss()));
            ar1.setSign("2");
            ar1.setOrderNo(outTradeNo);
            ar1.setInfo(customer.getAgentCode() + "参团成功! 消耗极乐值：" + product.getBliss());
            accountRecordDao.save(ar1);
        }

        int uu = (int) (couponPrice.doubleValue() / 9.9);
        if(uu > 0){
            UserCoupon uc = userCouponDao.queryByUserIdAndCouponId(userId, couponId);
            if(uc != null){
                uc.setQuantity(uc.getQuantity() - uu);
                userCouponDao.update(uc);

                AccountRecord ar2 = new AccountRecord();
                ar2.setOutUserId(userId);
                ar2.setUpdateTime(new Date());
                ar2.setType("5"); // 拼团券
                ar2.setAmount(new BigDecimal(uu));
                ar2.setNowAmount(new BigDecimal(uc.getQuantity()));
                ar2.setSign("2");
                ar2.setOrderNo(outTradeNo);
                ar2.setInfo(customer.getAgentCode() + "参团成功! 消费拼团券：" + uu);
                accountRecordDao.save(ar2);
            }
        }

        // 处理等级
        handleCollageLevel(customer, outTradeNo);

        System.err.println("准备要传入的参数 sku ---------------------------------- " + sku);
        System.err.println("准备要传入的参数 couponQuantity ---------------------------------- " + couponQuantity);

        /**
         * 处理团
         * @param collageMode
         * @param product
         * @param userId
         * @param totalAmount
         * @param totalPrice
         * @param consigneeName
         * @param fullAddress
         * @param consigneePhone
         * @param freight
         * @param couponPrice
         * @param couponQuantity
         * @param sku
         * @param isSpellSelect
         * @param couponId
         * @param outTradeNo
         * @param tradeNo
         * @throws ParseException
         */
        ordersCopyService.handleCollage(collageMode, product, userId, totalAmount, totalPrice, consigneeName, fullAddress, consigneePhone, freight,
                couponPrice, couponQuantity, skuId, isSpellSelect, couponId, outTradeNo, tradeNo);

        return ResponseServer.success("余额支付成功!!!");
    }


    /**
     * 购买拼团产品，微信支付
     * @param request
     * @param productId
     * @param openId
     * @param consigneeName
     * @param fullAddress
     * @param consigneePhone
     * @param userId
     * @param freight
     * @return
     */
    @PostMapping("/collage/pay")
    public ResponseServer collagePay(HttpServletRequest request, @RequestParam(required = false) Integer productId,
                                     @RequestParam(required = false) String openId,
                                     @RequestParam(required = false) String consigneeName,
                                     @RequestParam(required = false) String fullAddress,
                                     @RequestParam(required = false) String consigneePhone,
                                     @RequestParam(required = false) Integer userId,
                                     @RequestParam(required = false) BigDecimal freight,
                                     @RequestParam(required = false) BigDecimal couponPrice,
                                     @RequestParam(required = false) Integer couponQuantity,
                                     @RequestParam(required = false) Integer skuId,
                                     @RequestParam(required = false) boolean isSpellSelect,
                                     @RequestParam(required = false) Integer couponId) throws Exception {

        System.err.println("-------------创建订单传递的参数：productId= " + productId);
        System.err.println("-------------创建订单传递的参数：openId= " + openId);
        System.err.println("-------------创建订单传递的参数：consigneeName= " + consigneeName);
        System.err.println("-------------创建订单传递的参数：fullAddress= " + fullAddress);
        System.err.println("-------------创建订单传递的参数：consigneePhone= " + consigneePhone);
        System.err.println("-------------创建订单传递的参数：userId= " + userId);
        System.err.println("-------------创建订单传递的参数：freight= " + freight);
        System.err.println("-------------创建订单传递的参数：couponPrice= " + couponPrice);
        System.err.println("-------------创建订单传递的参数：couponQuantity= " + couponQuantity);
        System.err.println("-------------创建订单传递的参数：skuId= " + skuId);
        System.err.println("-------------创建订单传递的参数：isSpellSelect= " + isSpellSelect);
        System.err.println("-------------创建订单传递的参数：couponId= " + couponId);

        Map<String, String> maps = new HashMap<>();

        Product product = productDao.queryById(productId);
        if(product == null){
            maps.put("prepayId", "");
            maps.put("msg", "支付失败,产品信息错误");
            return ResponseServer.success(maps);
        }

        CollageMode collageMode = collageModeDao.queryById(product.getCollageModeId());
        if(collageMode == null){
            maps.put("prepayId", "");
            maps.put("msg", "支付失败,拼团模式错误");
            return ResponseServer.success(maps);
        }

        Customer customer = customerDao.queryById(userId);
        if(customer == null){
            maps.put("prepayId", "");
            maps.put("msg", "支付失败,用户信息错误");
            return ResponseServer.success(maps);
        }

        BigDecimal totalPrice; // 需要支付的金额
        // 商户订单号
        String outTradeNo = "BEE" + Units.getOrderIdByTime().replaceAll("-", "");
        // 交易号
        String tradeNo = "JYH" + Units.getOrderIdByTime().replaceAll("-", "");
        if (freight == null) {
            freight = BigDecimal.valueOf(0.0);
        }
        if(couponPrice == null){
            couponPrice = BigDecimal.valueOf(0.0);
        }
        SkuRelation sku = skuRelationDao.queryById(skuId);
        BigDecimal totalAmount = sku.getRetailPrice(); // 产品总金额
        totalPrice = sku.getRetailPrice().add(freight).subtract(couponPrice);
        Map<String, String> map;
        if (totalPrice.doubleValue() > 0) {
            Map<String, Object> wxPay = new HashMap<>();
            wxPay.put("totalPrice", totalPrice.doubleValue());
            wxPay.put("outTradeNo", outTradeNo);
            wxPay.put("openId", openId);
            wxPay.put("notifyUrl", Constants.notify_url_collage);
            wxPay.put("wxPayAppId", Constants.wxAppId);
            wxPay.put("tradeType", Constants.trade_type);
            String paramBuffer = CreateUnifiedOrder.UnifiedOrder(request, wxPay);
            map = Units.doXMLParse(HttpRequestUtil.sendPost(Constants.pay_url, new String(paramBuffer.getBytes(), "UTF-8")));
            if (map != null) {
                // 创建订单
                Orders orders = new Orders();
                orders.setOrderNo(outTradeNo);
                orders.setTradeNo(tradeNo);
                orders.setTotalAmount(totalAmount);
                orders.setPayAmount(totalPrice);
                orders.setCouponAmount(couponPrice);
                orders.setFreight(freight);
                orders.setPayStatus("0");
                orders.setPayType("0");
                orders.setDealStatus("0"); // 等待开团
                orders.setRefundStatus("0");
                orders.setCollageModeId(product.getCollageModeId());
                orders.setModeName(collageMode.getName());
                orders.setProductId(product.getId());
                //orders.setModeProductId(newMP.getId());
                orders.setOrderPersonId(userId);
                orders.setConsigneeName(consigneeName);
                orders.setConsigneePhone(consigneePhone);
                orders.setAddress(fullAddress);
                orders.setPrepayId(map.get("prepay_id"));
                orders.setUpdateTime(new Date());
                orders.setIsDel("0");
                orders.setIsRun("0");
                if(isSpellSelect){
                    orders.setLastCollage("1");
                }else{
                    orders.setLastCollage("0");
                }
                orders.setRemarks("无");
                ordersDao.save(orders);

                // 订单详情
                OrderDetails od = new OrderDetails();
                od.setOrderNo(orders.getOrderNo());
                od.setTradeNo(orders.getTradeNo());
                od.setStoreShopId(product.getStoreShopId());
                od.setStoreShopName(storeShopDao.queryById(product.getStoreShopId()).getName());
                od.setClassifyId(product.getClassifyId());
                od.setClassifyName(classifyDao.queryById(product.getClassifyId()).getName());
                od.setProductId(product.getId());
                od.setProductType(product.getType());
                od.setProductImg(product.getImg());
                od.setProductName(product.getName());
                od.setProductCode(product.getProductCode());
                od.setCostPrice(sku.getCostPrice());
                od.setRelationId(sku.getId());
                if(sku.getGroupRelation().contains(",")){
                    String[] strings = sku.getGroupRelation().split(",");
                    String str = "";
                    for(int u = 0; u < strings.length; u++){
                        str += specAttributeDao.queryById(Integer.parseInt(strings[u])).getAttributeName() + "，";
                    }
                    od.setSpecAttributeName(str.substring(0, str.length()-1));
                }else{
                    od.setSpecAttributeName(specAttributeDao.queryById(Integer.parseInt(sku.getGroupRelation())).getAttributeName());
                }
                od.setQuantity(1);
                od.setUnitPrice(sku.getRetailPrice());
                od.setUpdateTime(new Date());
                orderDetailsDao.save(od);

                maps.put("prepayId", map.get("prepay_id"));
                maps.put("outTradeNo", outTradeNo);
                return ResponseServer.success(maps);
            }
        }
        maps.put("prepayId", "");
        maps.put("msg", "支付失败,请重试");
        return ResponseServer.success(maps);
    }


    /**
     * 拼团支付成功后回调
     * @param request
     * @param response
     */
    @PostMapping("/notify_url_collage")
    public void collagePayCallback(HttpServletRequest request, HttpServletResponse response) {
        System.err.println("微信回调接口方法 start ----------------------------");
        String inputLine = "";
        String notityXml = "";
        try {
            while ((inputLine = request.getReader().readLine()) != null) {
                notityXml += inputLine;
            }
            // 关闭流
            request.getReader().close();
            System.err.println("小程序商城支付回调：" + notityXml);
            // 解析成Map
            Map<String, String> map = Units.doXMLParse(notityXml);
            System.err.println(map);
            // 判断 支付是否成功
            if ("SUCCESS".equals(map.get("result_code"))) {
                System.err.println("微信回调返回是否支付成功：是");
                // 获得 返回的商户订单号
                String outTradeNo = map.get("out_trade_no");

                Orders orders = ordersDao.queryByOrderNo(outTradeNo);
                orders.setPayStatus("1");
                orders.setDealStatus("6");
                ordersDao.update(orders);

                Customer customer = customerDao.queryById(orders.getOrderPersonId());

                CollageMode collageMode = collageModeDao.queryById(orders.getCollageModeId());

                Product product = productDao.queryById(orders.getProductId());
                product.setSales(product.getSales() + 1); // 添加销量
                productDao.update(product);

                int couponQuantity = (int)(orders.getCouponAmount().doubleValue() / 9.9);
                OrderDetails orderDetails = orderDetailsDao.queryByOrderNo(outTradeNo);

                // 处理等级
                handleCollageLevel(customer, outTradeNo);

                // 处理团
                ordersCopyService.handleCollage_wx(orders, collageMode, product, customer.getId(), couponQuantity, orderDetails.getRelationId(), 1);

                // 封装 返回值
                StringBuffer buffer = new StringBuffer();
                buffer.append("<xml>");
                buffer.append("<return_code>SUCCESS</return_code>");
                buffer.append("<return_msg>OK</return_msg>");
                buffer.append("</xml>");
                // 给微信服务器返回 成功标示 否则会一直询问服务器是否回调成功
                PrintWriter writer = response.getWriter();
                // 返回
                writer.print(buffer.toString());
            }
        } catch (IOException e) {
            e.printStackTrace();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }


    /**
     * 购买拼团产品参数
     * @param productId
     * @return
     */
    @GetMapping("/getConfirmCollageProductData")
    public ResponseServer getConfirmCollageProductData(Integer productId, Integer skuId){
        ConfirmProductDTO dto = productDao.queryProductById1(productId);
        SkuRelation sku = skuRelationDao.queryById(skuId);
        dto.setSkuId(sku.getId());
        dto.setRetailPrice(sku.getRetailPrice());
        if(sku.getGroupRelation().contains(",")){
            String[] strings = sku.getGroupRelation().split(",");
            String str = "";
            for(int u = 0; u < strings.length; u++){
                str += specAttributeDao.queryById(Integer.parseInt(strings[u])).getAttributeName() + "，";
            }
            dto.setSpecAttributeName(str.substring(0, str.length()-1));
        }else{
            dto.setSpecAttributeName(specAttributeDao.queryById(Integer.parseInt(sku.getGroupRelation())).getAttributeName());
        }
        dto.setQuantity(1);
        List<StoreShopFreightVO> voList = storeShopFreightDao.queryStoreShopFreightVOById(dto.getStoreShopId());
        dto.setStoreShopFreightVOList(voList);
        return ResponseServer.success(dto);
    }


    /**
     * 购买拼团产品参数，并获取个人极乐值
     * @param userId
     * @return
     */
    @GetMapping("/getCustomerAccountBlissData")
    public ResponseServer getCustomerAccountBlissData(Integer userId){
        Account account = accountDao.queryAccountByUserId(userId);
        return ResponseServer.success(account);
    }


    /**
     * 处理参与拼团后的等级
     * @param customer
     */
    public void handleCollageLevel(Customer customer, String orderNo){
        if(customer.getLevelId() == 1){ //游客
            customer.setLevelId(2); // 升会员
            if("0".equals(customer.getIsActive())){
                customer.setIsActive("1"); // 激活拼团等级
            }
            // 同步共享等级
            customer.setLevelCopyId(2);
            if("0".equals(customer.getIsActiveCopy())){
                // 是否购买过共享产品
                List<Orders> ordersList = ordersDao.queryOrdersByUserIdIsBuyShare(customer.getId());
                if(ordersList.size() > 0){
                    customer.setIsActiveCopy("1"); // 激活共享等级
                }
            }
            // TODO 直播等级 等待完善
            // 同步直播等级
            customer.setLevelCopy1Id(2);
            // 判断是否购买过直播产品，买过就激活
            customer.setIsActiveCopy1("0"); // 待激活直播等级

            // 同步蜜淘等级
            customer.setLevelCopy2Id(2);
            if("0".equals(customer.getIsActiveCopy2())){
                // 是否购买过蜜淘产品
                List<GoodsOrders> ordersList = goodsOrdersDao.queryGoodsOrdersByUserIdIsBuyBeeAmoy(customer.getId());
                if(ordersList.size() > 0){
                    customer.setIsActive("1"); // 激活蜜淘等级
                }
            }

            customerDao.update(customer);

            if(customer.getParentId() != null && customer.getParentId() != 1198 && customer.getLevelId() != 7){
                Customer parentCustomer = customerDao.queryById(customer.getParentId());
                if(parentCustomer != null){

                    Account pa = accountDao.queryAccountByUserId(parentCustomer.getId());
                    pa.setBliss(pa.getBliss() + 9);
                    accountDao.update(pa);
                    AccountRecord ar = new AccountRecord();
                    ar.setIntoUserId(parentCustomer.getId());
                    ar.setOrderNo(orderNo);
                    ar.setType("2");
                    ar.setSign("1");
                    ar.setUpdateTime(new Date());
                    ar.setAmount(new BigDecimal(9));
                    ar.setNowAmount(new BigDecimal(pa.getBliss()));
                    ar.setInfo(customer.getAgentCode() + "参团成功! 您获极乐值：" + 9);
                    accountRecordDao.save(ar);

                    if(parentCustomer.getParentId() != null && parentCustomer.getParentId() != 1198 && parentCustomer.getLevelId() != 7){
                        Customer ppc = customerDao.queryById(parentCustomer.getParentId());
                        if(ppc != null){
                            Account ppa = accountDao.queryAccountByUserId(ppc.getId());
                            ppa.setBliss(ppa.getBliss() + 6);
                            accountDao.update(ppa);
                            AccountRecord arp = new AccountRecord();
                            arp.setIntoUserId(ppc.getId());
                            arp.setOrderNo(orderNo);
                            arp.setType("2");
                            arp.setSign("1");
                            arp.setUpdateTime(new Date());
                            arp.setAmount(new BigDecimal(6));
                            arp.setNowAmount(new BigDecimal(ppa.getBliss()));
                            arp.setInfo(customer.getAgentCode() + "参团成功! 您获极乐值：" + 6);
                            accountRecordDao.save(arp);
                        }
                    }


                    if(parentCustomer.getLevelId() == 1){ // 游客

                    }else if(parentCustomer.getLevelId() == 2){ // 会员
                        // 判断是否直接推荐了9个会员
                        int count = customerDao.queryCustomerByLevelIdAndParentId(2, parentCustomer.getId());
                        if(count > 8){
                            parentCustomer.setLevelId(3); // 升小咖

                            // 同步共享等级
                            parentCustomer.setLevelCopyId(3);
                            if("0".equals(parentCustomer.getIsActiveCopy())){
                                // 是否购买过共享产品
                                List<Orders> ordersList = ordersDao.queryOrdersByUserIdIsBuyShare(parentCustomer.getId());
                                if(ordersList.size() > 0){
                                    parentCustomer.setIsActiveCopy("1"); // 激活共享等级
                                }
                            }
                            // TODO 直播等级 等待完善
                            // 同步直播等级
                            parentCustomer.setLevelCopy1Id(3);
                            // 判断是否购买过直播产品，买过就激活
                            parentCustomer.setIsActiveCopy1("0"); // 待激活直播等级

                            // 同步蜜淘等级
                            parentCustomer.setLevelCopy2Id(3);
                            if("0".equals(parentCustomer.getIsActiveCopy2())){
                                // 是否购买过蜜淘产品
                                List<GoodsOrders> ordersList = goodsOrdersDao.queryGoodsOrdersByUserIdIsBuyBeeAmoy(parentCustomer.getId());
                                if(ordersList.size() > 0){
                                    parentCustomer.setIsActive("1"); // 激活蜜淘等级
                                    if(parentCustomer.getAddUpUpgrade().doubleValue() < 10000){
                                        parentCustomer.setAddUpUpgradeFiction(BigDecimal.valueOf(10000).subtract(parentCustomer.getAddUpUpgrade()).add(parentCustomer.getAddUpUpgradeFiction()));
                                    }
                                }
                            }

                            customerDao.update(parentCustomer);

                            if(parentCustomer.getParentId() != null && parentCustomer.getParentId() != 1198 && parentCustomer.getLevelId() != 7){
                                Customer top3Customer = customerDao.queryById(parentCustomer.getParentId());
                                if(top3Customer != null){
                                    if(top3Customer.getLevelId() == 1){

                                    }else if(top3Customer.getLevelId() == 2){

                                    }else if(top3Customer.getLevelId() == 3){
                                        // 判断是否直接推荐了9个小咖
                                        int top3Count = customerDao.queryCustomerByLevelIdAndParentId(3, parentCustomer.getId());
                                        if(top3Count > 8) {
                                            top3Customer.setLevelId(4); // 升网红

                                            // 同步共享等级
                                            top3Customer.setLevelCopyId(4);
                                            if("0".equals(top3Customer.getIsActiveCopy())){
                                                // 是否购买过共享产品
                                                List<Orders> ordersList = ordersDao.queryOrdersByUserIdIsBuyShare(top3Customer.getId());
                                                if(ordersList.size() > 0){
                                                    top3Customer.setIsActiveCopy("1"); // 激活共享等级
                                                }
                                            }
                                            // TODO 直播等级 等待完善
                                            // 同步直播等级
                                            top3Customer.setLevelCopy1Id(4);
                                            // 判断是否购买过直播产品，买过就激活
                                            top3Customer.setIsActiveCopy1("0"); // 待激活直播等级

                                            // 同步蜜淘等级
                                            top3Customer.setLevelCopy2Id(4);
                                            if("0".equals(top3Customer.getIsActiveCopy2())){
                                                // 是否购买过蜜淘产品
                                                List<GoodsOrders> ordersList = goodsOrdersDao.queryGoodsOrdersByUserIdIsBuyBeeAmoy(top3Customer.getId());
                                                if(ordersList.size() > 0){
                                                    top3Customer.setIsActive("1"); // 激活蜜淘等级
                                                    if(top3Customer.getAddUpUpgrade().doubleValue() < 50000){
                                                        top3Customer.setAddUpUpgradeFiction(BigDecimal.valueOf(50000).subtract(top3Customer.getAddUpUpgrade()).add(top3Customer.getAddUpUpgradeFiction()));
                                                    }
                                                }
                                            }

                                            customerDao.update(top3Customer);

                                            if(top3Customer.getParentId() != null && top3Customer.getParentId() != 1198 && top3Customer.getLevelId() != 7){
                                                Customer top4Customer = customerDao.queryById(top3Customer.getParentId());
                                                if(top4Customer != null){
                                                    if(top4Customer.getLevelId() == 1){

                                                    }else if(top4Customer.getLevelId() == 2){

                                                    }else if(top4Customer.getLevelId() == 3){

                                                    }else if(top4Customer.getLevelId() == 4){
                                                        // 判断是否直接推荐了9个网红
                                                        int top4Count = customerDao.queryCustomerByLevelIdAndParentId(4, top4Customer.getId());
                                                        if(top4Count > 8) {
                                                            top4Customer.setLevelId(5); // 升明星

                                                            // 同步共享等级
                                                            top4Customer.setLevelCopyId(5);
                                                            if("0".equals(top4Customer.getIsActiveCopy())){
                                                                // 是否购买过共享产品
                                                                List<Orders> ordersList = ordersDao.queryOrdersByUserIdIsBuyShare(top4Customer.getId());
                                                                if(ordersList.size() > 0){
                                                                    top4Customer.setIsActiveCopy("1"); // 激活共享等级
                                                                }
                                                            }
                                                            // TODO 直播等级 等待完善
                                                            // 同步直播等级
                                                            top4Customer.setLevelCopy1Id(5);
                                                            // 判断是否购买过直播产品，买过就激活
                                                            top4Customer.setIsActiveCopy1("0"); // 待激活直播等级

                                                            // 同步蜜淘等级
                                                            top4Customer.setLevelCopy2Id(5);
                                                            if("0".equals(top4Customer.getIsActiveCopy2())){
                                                                // 是否购买过蜜淘产品
                                                                List<GoodsOrders> ordersList = goodsOrdersDao.queryGoodsOrdersByUserIdIsBuyBeeAmoy(top4Customer.getId());
                                                                if(ordersList.size() > 0){
                                                                    top4Customer.setIsActive("1"); // 激活蜜淘等级
                                                                    if(top4Customer.getAddUpUpgrade().doubleValue() < 100000){
                                                                        top4Customer.setAddUpUpgradeFiction(BigDecimal.valueOf(100000).subtract(top4Customer.getAddUpUpgrade()).add(top4Customer.getAddUpUpgradeFiction()));
                                                                    }
                                                                }
                                                            }

                                                            customerDao.update(top4Customer);

                                                            if(top4Customer.getParentId() != null && top4Customer.getParentId() != 1198 && top4Customer.getLevelId() != 7){
                                                                Customer top5Customer = customerDao.queryById(top4Customer.getParentId());
                                                                if(top5Customer != null){
                                                                    if(top5Customer.getLevelId() == 1){

                                                                    }else if(top5Customer.getLevelId() == 2){

                                                                    }else if(top5Customer.getLevelId() == 3){

                                                                    }else if(top5Customer.getLevelId() == 4){

                                                                    }else if(top5Customer.getLevelId() == 5){
                                                                        // 判断是否直接推荐了9个明星
                                                                        int top5Count = customerDao.queryCustomerByLevelIdAndParentId(5, top5Customer.getId());
                                                                        if(top5Count > 8) {
                                                                            top5Customer.setLevelId(6); // 升大腕

                                                                            // 同步共享等级
                                                                            top5Customer.setLevelCopyId(6);
                                                                            if("0".equals(top5Customer.getIsActiveCopy())){
                                                                                // 是否购买过共享产品
                                                                                List<Orders> ordersList = ordersDao.queryOrdersByUserIdIsBuyShare(top5Customer.getId());
                                                                                if(ordersList.size() > 0){
                                                                                    top5Customer.setIsActiveCopy("1"); // 激活共享等级
                                                                                }
                                                                            }
                                                                            // TODO 直播等级 等待完善
                                                                            // 同步直播等级
                                                                            top5Customer.setLevelCopy1Id(6);
                                                                            // 判断是否购买过直播产品，买过就激活
                                                                            top5Customer.setIsActiveCopy1("0"); // 待激活直播等级

                                                                            // 同步蜜淘等级
                                                                            top5Customer.setLevelCopy2Id(6);
                                                                            if("0".equals(top5Customer.getIsActiveCopy2())){
                                                                                // 是否购买过蜜淘产品
                                                                                List<GoodsOrders> ordersList = goodsOrdersDao.queryGoodsOrdersByUserIdIsBuyBeeAmoy(top5Customer.getId());
                                                                                if(ordersList.size() > 0){
                                                                                    top5Customer.setIsActive("1"); // 激活蜜淘等级
                                                                                    if(top5Customer.getAddUpUpgrade().doubleValue() < 200000){
                                                                                        top5Customer.setAddUpUpgradeFiction(BigDecimal.valueOf(200000).subtract(top5Customer.getAddUpUpgrade()).add(top5Customer.getAddUpUpgradeFiction()));
                                                                                    }
                                                                                }
                                                                            }

                                                                            customerDao.update(top5Customer);
                                                                        }else{

                                                                        }
                                                                    }
                                                                }
                                                            }
                                                        }else{

                                                        }

                                                    }else if(top4Customer.getLevelId() == 5){
                                                        // 判断是否直接推荐了9个明星
                                                        int top5Count = customerDao.queryCustomerByLevelIdAndParentId(5, top4Customer.getId());
                                                        if(top5Count > 8) {
                                                            top4Customer.setLevelId(6); // 升大腕

                                                            // 同步共享等级
                                                            top4Customer.setLevelCopyId(6);
                                                            if("0".equals(top4Customer.getIsActiveCopy())){
                                                                // 是否购买过共享产品
                                                                List<Orders> ordersList = ordersDao.queryOrdersByUserIdIsBuyShare(top4Customer.getId());
                                                                if(ordersList.size() > 0){
                                                                    top4Customer.setIsActiveCopy("1"); // 激活共享等级
                                                                }
                                                            }
                                                            // TODO 直播等级 等待完善
                                                            // 同步直播等级
                                                            top4Customer.setLevelCopy1Id(6);
                                                            // 判断是否购买过直播产品，买过就激活
                                                            top4Customer.setIsActiveCopy1("0"); // 待激活直播等级

                                                            // 同步蜜淘等级
                                                            top4Customer.setLevelCopy2Id(6);
                                                            if("0".equals(top4Customer.getIsActiveCopy2())){
                                                                // 是否购买过蜜淘产品
                                                                List<GoodsOrders> ordersList = goodsOrdersDao.queryGoodsOrdersByUserIdIsBuyBeeAmoy(top4Customer.getId());
                                                                if(ordersList.size() > 0){
                                                                    top4Customer.setIsActive("1"); // 激活蜜淘等级
                                                                    if(top4Customer.getAddUpUpgrade().doubleValue() < 200000){
                                                                        top4Customer.setAddUpUpgradeFiction(BigDecimal.valueOf(200000).subtract(top4Customer.getAddUpUpgrade()).add(top4Customer.getAddUpUpgradeFiction()));
                                                                    }
                                                                }
                                                            }

                                                            customerDao.update(top4Customer);
                                                        }else{

                                                        }
                                                    }
                                                }
                                            }
                                        }else{

                                        }

                                    }else if(top3Customer.getLevelId() == 4){
                                        // 判断是否直接推荐了9个网红
                                        int top4Count = customerDao.queryCustomerByLevelIdAndParentId(4, top3Customer.getId());
                                        if(top4Count > 8) {
                                            top3Customer.setLevelId(5); // 升明星

                                            // 同步共享等级
                                            top3Customer.setLevelCopyId(5);
                                            if("0".equals(top3Customer.getIsActiveCopy())){
                                                // 是否购买过共享产品
                                                List<Orders> ordersList = ordersDao.queryOrdersByUserIdIsBuyShare(top3Customer.getId());
                                                if(ordersList.size() > 0){
                                                    top3Customer.setIsActiveCopy("1"); // 激活共享等级
                                                }
                                            }
                                            // TODO 直播等级 等待完善
                                            // 同步直播等级
                                            top3Customer.setLevelCopy1Id(5);
                                            // 判断是否购买过直播产品，买过就激活
                                            top3Customer.setIsActiveCopy1("0"); // 待激活直播等级

                                            // 同步蜜淘等级
                                            top3Customer.setLevelCopy2Id(5);
                                            if("0".equals(top3Customer.getIsActiveCopy2())){
                                                // 是否购买过蜜淘产品
                                                List<GoodsOrders> ordersList = goodsOrdersDao.queryGoodsOrdersByUserIdIsBuyBeeAmoy(top3Customer.getId());
                                                if(ordersList.size() > 0){
                                                    top3Customer.setIsActive("1"); // 激活蜜淘等级
                                                    if(top3Customer.getAddUpUpgrade().doubleValue() < 100000){
                                                        top3Customer.setAddUpUpgradeFiction(BigDecimal.valueOf(100000).subtract(top3Customer.getAddUpUpgrade()).add(top3Customer.getAddUpUpgradeFiction()));
                                                    }
                                                }
                                            }

                                            customerDao.update(top3Customer);

                                            if(top3Customer.getParentId() != null && top3Customer.getParentId() != 1198 && top3Customer.getLevelId() != 7){
                                                Customer top5Customer = customerDao.queryById(top3Customer.getParentId());
                                                if(top5Customer != null){
                                                    if(top5Customer.getLevelId() == 1){

                                                    }else if(top5Customer.getLevelId() == 2){

                                                    }else if(top5Customer.getLevelId() == 3){

                                                    }else if(top5Customer.getLevelId() == 4){

                                                    }else if(top5Customer.getLevelId() == 5){
                                                        // 判断是否直接推荐了9个明星
                                                        int top5Count = customerDao.queryCustomerByLevelIdAndParentId(5, top5Customer.getId());
                                                        if(top5Count > 8) {
                                                            top5Customer.setLevelId(6); // 升大腕

                                                            // 同步共享等级
                                                            top5Customer.setLevelCopyId(6);
                                                            if("0".equals(top5Customer.getIsActiveCopy())){
                                                                // 是否购买过共享产品
                                                                List<Orders> ordersList = ordersDao.queryOrdersByUserIdIsBuyShare(top5Customer.getId());
                                                                if(ordersList.size() > 0){
                                                                    top5Customer.setIsActiveCopy("1"); // 激活共享等级
                                                                }
                                                            }
                                                            // TODO 直播等级 等待完善
                                                            // 同步直播等级
                                                            top5Customer.setLevelCopy1Id(6);
                                                            // 判断是否购买过直播产品，买过就激活
                                                            top5Customer.setIsActiveCopy1("0"); // 待激活直播等级

                                                            // 同步蜜淘等级
                                                            top5Customer.setLevelCopy2Id(6);
                                                            if("0".equals(top5Customer.getIsActiveCopy2())){
                                                                // 是否购买过蜜淘产品
                                                                List<GoodsOrders> ordersList = goodsOrdersDao.queryGoodsOrdersByUserIdIsBuyBeeAmoy(top5Customer.getId());
                                                                if(ordersList.size() > 0){
                                                                    top5Customer.setIsActive("1"); // 激活蜜淘等级
                                                                    if(top5Customer.getAddUpUpgrade().doubleValue() < 200000){
                                                                        top5Customer.setAddUpUpgradeFiction(BigDecimal.valueOf(200000).subtract(top5Customer.getAddUpUpgrade()).add(top5Customer.getAddUpUpgradeFiction()));
                                                                    }
                                                                }
                                                            }

                                                            customerDao.update(top5Customer);
                                                        }else{

                                                        }
                                                    }
                                                }
                                            }
                                        }else{

                                        }
                                    }else if(top3Customer.getLevelId() == 5){
                                        // 判断是否直接推荐了9个明星
                                        int top5Count = customerDao.queryCustomerByLevelIdAndParentId(5, top3Customer.getId());
                                        if(top5Count > 8) {
                                            top3Customer.setLevelId(6); // 升大腕

                                            // 同步共享等级
                                            top3Customer.setLevelCopyId(6);
                                            if("0".equals(top3Customer.getIsActiveCopy())){
                                                // 是否购买过共享产品
                                                List<Orders> ordersList = ordersDao.queryOrdersByUserIdIsBuyShare(top3Customer.getId());
                                                if(ordersList.size() > 0){
                                                    top3Customer.setIsActiveCopy("1"); // 激活共享等级
                                                }
                                            }
                                            // TODO 直播等级 等待完善
                                            // 同步直播等级
                                            top3Customer.setLevelCopy1Id(6);
                                            // 判断是否购买过直播产品，买过就激活
                                            top3Customer.setIsActiveCopy1("0"); // 待激活直播等级

                                            // 同步蜜淘等级
                                            top3Customer.setLevelCopy2Id(6);
                                            if("0".equals(top3Customer.getIsActiveCopy2())){
                                                // 是否购买过蜜淘产品
                                                List<GoodsOrders> ordersList = goodsOrdersDao.queryGoodsOrdersByUserIdIsBuyBeeAmoy(top3Customer.getId());
                                                if(ordersList.size() > 0){
                                                    top3Customer.setIsActive("1"); // 激活蜜淘等级
                                                    if(top3Customer.getAddUpUpgrade().doubleValue() < 200000){
                                                        top3Customer.setAddUpUpgradeFiction(BigDecimal.valueOf(200000).subtract(top3Customer.getAddUpUpgrade()).add(top3Customer.getAddUpUpgradeFiction()));
                                                    }
                                                }
                                            }

                                            customerDao.update(top3Customer);
                                        }else{

                                        }
                                    }
                                }
                            }
                        }else{

                        }

                    }else if(parentCustomer.getLevelId() == 3){ // 小咖
                        // 判断是否直接推荐了9个小咖
                        int top3Count = customerDao.queryCustomerByLevelIdAndParentId(3, parentCustomer.getId());
                        if(top3Count > 8) {
                            parentCustomer.setLevelId(4); // 升网红

                            // 同步共享等级
                            parentCustomer.setLevelCopyId(4);
                            if("0".equals(parentCustomer.getIsActiveCopy())){
                                // 是否购买过共享产品
                                List<Orders> ordersList = ordersDao.queryOrdersByUserIdIsBuyShare(parentCustomer.getId());
                                if(ordersList.size() > 0){
                                    parentCustomer.setIsActiveCopy("1"); // 激活共享等级
                                }
                            }
                            // TODO 直播等级 等待完善
                            // 同步直播等级
                            parentCustomer.setLevelCopy1Id(4);
                            // 判断是否购买过直播产品，买过就激活
                            parentCustomer.setIsActiveCopy1("0"); // 待激活直播等级

                            // 同步蜜淘等级
                            parentCustomer.setLevelCopy2Id(4);
                            if("0".equals(parentCustomer.getIsActiveCopy2())){
                                // 是否购买过蜜淘产品
                                List<GoodsOrders> ordersList = goodsOrdersDao.queryGoodsOrdersByUserIdIsBuyBeeAmoy(parentCustomer.getId());
                                if(ordersList.size() > 0){
                                    parentCustomer.setIsActive("1"); // 激活蜜淘等级
                                    if(parentCustomer.getAddUpUpgrade().doubleValue() < 50000){
                                        parentCustomer.setAddUpUpgradeFiction(BigDecimal.valueOf(50000).subtract(parentCustomer.getAddUpUpgrade()).add(parentCustomer.getAddUpUpgradeFiction()));
                                    }
                                }
                            }

                            customerDao.update(parentCustomer);

                            if(parentCustomer.getParentId() != null && parentCustomer.getParentId() != 1198 && parentCustomer.getLevelId() != 7){
                                Customer top4Customer = customerDao.queryById(parentCustomer.getParentId());
                                if(top4Customer != null){
                                    if(top4Customer.getLevelId() == 1){

                                    }else if(top4Customer.getLevelId() == 2){

                                    }else if(top4Customer.getLevelId() == 3){

                                    }else if(top4Customer.getLevelId() == 4){
                                        // 判断是否直接推荐了9个网红
                                        int top4Count = customerDao.queryCustomerByLevelIdAndParentId(4, top4Customer.getId());
                                        if(top4Count > 8) {
                                            top4Customer.setLevelId(5); // 升明星

                                            // 同步共享等级
                                            top4Customer.setLevelCopyId(5);
                                            if("0".equals(top4Customer.getIsActiveCopy())){
                                                // 是否购买过共享产品
                                                List<Orders> ordersList = ordersDao.queryOrdersByUserIdIsBuyShare(top4Customer.getId());
                                                if(ordersList.size() > 0){
                                                    top4Customer.setIsActiveCopy("1"); // 激活共享等级
                                                }
                                            }
                                            // TODO 直播等级 等待完善
                                            // 同步直播等级
                                            top4Customer.setLevelCopy1Id(5);
                                            // 判断是否购买过直播产品，买过就激活
                                            top4Customer.setIsActiveCopy1("0"); // 待激活直播等级

                                            // 同步蜜淘等级
                                            top4Customer.setLevelCopy2Id(5);
                                            if("0".equals(top4Customer.getIsActiveCopy2())){
                                                // 是否购买过蜜淘产品
                                                List<GoodsOrders> ordersList = goodsOrdersDao.queryGoodsOrdersByUserIdIsBuyBeeAmoy(top4Customer.getId());
                                                if(ordersList.size() > 0){
                                                    top4Customer.setIsActive("1"); // 激活蜜淘等级
                                                    if(top4Customer.getAddUpUpgrade().doubleValue() < 100000){
                                                        top4Customer.setAddUpUpgradeFiction(BigDecimal.valueOf(100000).subtract(top4Customer.getAddUpUpgrade()).add(top4Customer.getAddUpUpgradeFiction()));
                                                    }
                                                }
                                            }

                                            customerDao.update(top4Customer);

                                            if(top4Customer.getParentId() != null && top4Customer.getParentId() != 1198 && top4Customer.getLevelId() != 7){
                                                Customer top5Customer = customerDao.queryById(top4Customer.getParentId());
                                                if(top5Customer != null){
                                                    if(top5Customer.getLevelId() == 1){

                                                    }else if(top5Customer.getLevelId() == 2){

                                                    }else if(top5Customer.getLevelId() == 3){

                                                    }else if(top5Customer.getLevelId() == 4){

                                                    }else if(top5Customer.getLevelId() == 5){
                                                        // 判断是否直接推荐了9个明星
                                                        int top5Count = customerDao.queryCustomerByLevelIdAndParentId(5, top5Customer.getId());
                                                        if(top5Count > 8) {
                                                            top5Customer.setLevelId(6); // 升大腕

                                                            // 同步共享等级
                                                            top5Customer.setLevelCopyId(6);
                                                            if("0".equals(top5Customer.getIsActiveCopy())){
                                                                // 是否购买过共享产品
                                                                List<Orders> ordersList = ordersDao.queryOrdersByUserIdIsBuyShare(top5Customer.getId());
                                                                if(ordersList.size() > 0){
                                                                    top5Customer.setIsActiveCopy("1"); // 激活共享等级
                                                                }
                                                            }
                                                            // TODO 直播等级 等待完善
                                                            // 同步直播等级
                                                            top5Customer.setLevelCopy1Id(6);
                                                            // 判断是否购买过直播产品，买过就激活
                                                            top5Customer.setIsActiveCopy1("0"); // 待激活直播等级

                                                            // 同步蜜淘等级
                                                            top5Customer.setLevelCopy2Id(6);
                                                            if("0".equals(top5Customer.getIsActiveCopy2())){
                                                                // 是否购买过蜜淘产品
                                                                List<GoodsOrders> ordersList = goodsOrdersDao.queryGoodsOrdersByUserIdIsBuyBeeAmoy(top5Customer.getId());
                                                                if(ordersList.size() > 0){
                                                                    top5Customer.setIsActive("1"); // 激活蜜淘等级
                                                                    if(top5Customer.getAddUpUpgrade().doubleValue() < 200000){
                                                                        top5Customer.setAddUpUpgradeFiction(BigDecimal.valueOf(200000).subtract(top5Customer.getAddUpUpgrade()).add(top5Customer.getAddUpUpgradeFiction()));
                                                                    }
                                                                }
                                                            }

                                                            customerDao.update(top5Customer);
                                                        }else{

                                                        }
                                                    }
                                                }
                                            }
                                        }else{

                                        }
                                    }else if(top4Customer.getLevelId() == 5){
                                        // 判断是否直接推荐了9个明星
                                        int top5Count = customerDao.queryCustomerByLevelIdAndParentId(5, top4Customer.getId());
                                        if(top5Count > 8) {
                                            top4Customer.setLevelId(6); // 升大腕

                                            // 同步共享等级
                                            top4Customer.setLevelCopyId(6);
                                            if("0".equals(top4Customer.getIsActiveCopy())){
                                                // 是否购买过共享产品
                                                List<Orders> ordersList = ordersDao.queryOrdersByUserIdIsBuyShare(top4Customer.getId());
                                                if(ordersList.size() > 0){
                                                    top4Customer.setIsActiveCopy("1"); // 激活共享等级
                                                }
                                            }
                                            // TODO 直播等级 等待完善
                                            // 同步直播等级
                                            top4Customer.setLevelCopy1Id(6);
                                            // 判断是否购买过直播产品，买过就激活
                                            top4Customer.setIsActiveCopy1("0"); // 待激活直播等级

                                            // 同步蜜淘等级
                                            top4Customer.setLevelCopy2Id(6);
                                            if("0".equals(top4Customer.getIsActiveCopy2())){
                                                // 是否购买过蜜淘产品
                                                List<GoodsOrders> ordersList = goodsOrdersDao.queryGoodsOrdersByUserIdIsBuyBeeAmoy(top4Customer.getId());
                                                if(ordersList.size() > 0){
                                                    top4Customer.setIsActive("1"); // 激活蜜淘等级
                                                    if(top4Customer.getAddUpUpgrade().doubleValue() < 200000){
                                                        top4Customer.setAddUpUpgradeFiction(BigDecimal.valueOf(200000).subtract(top4Customer.getAddUpUpgrade()).add(top4Customer.getAddUpUpgradeFiction()));
                                                    }
                                                }
                                            }

                                            customerDao.update(top4Customer);
                                        }else{

                                        }
                                    }
                                }
                            }
                        }else{

                        }

                    }else if(parentCustomer.getLevelId() == 4){ // 网红
                        // 判断是否直接推荐了9个网红
                        int top4Count = customerDao.queryCustomerByLevelIdAndParentId(4, parentCustomer.getId());
                        if(top4Count > 8) {
                            parentCustomer.setLevelId(5); // 升明星

                            // 同步共享等级
                            parentCustomer.setLevelCopyId(5);
                            if("0".equals(parentCustomer.getIsActiveCopy())){
                                // 是否购买过共享产品
                                List<Orders> ordersList = ordersDao.queryOrdersByUserIdIsBuyShare(parentCustomer.getId());
                                if(ordersList.size() > 0){
                                    parentCustomer.setIsActiveCopy("1"); // 激活共享等级
                                }
                            }
                            // TODO 直播等级 等待完善
                            // 同步直播等级
                            parentCustomer.setLevelCopy1Id(5);
                            // 判断是否购买过直播产品，买过就激活
                            parentCustomer.setIsActiveCopy1("0"); // 待激活直播等级

                            // 同步蜜淘等级
                            parentCustomer.setLevelCopy2Id(5);
                            if("0".equals(parentCustomer.getIsActiveCopy2())){
                                // 是否购买过蜜淘产品
                                List<GoodsOrders> ordersList = goodsOrdersDao.queryGoodsOrdersByUserIdIsBuyBeeAmoy(parentCustomer.getId());
                                if(ordersList.size() > 0){
                                    parentCustomer.setIsActive("1"); // 激活蜜淘等级
                                    if(parentCustomer.getAddUpUpgrade().doubleValue() < 100000){
                                        parentCustomer.setAddUpUpgradeFiction(BigDecimal.valueOf(100000).subtract(parentCustomer.getAddUpUpgrade()).add(parentCustomer.getAddUpUpgradeFiction()));
                                    }
                                }
                            }

                            customerDao.update(parentCustomer);

                            if(parentCustomer.getParentId() != null && parentCustomer.getParentId() != 1198 && parentCustomer.getLevelId() != 7){
                                Customer top5Customer = customerDao.queryById(parentCustomer.getParentId());
                                if(top5Customer != null){
                                    if(top5Customer.getLevelId() == 1){

                                    }else if(top5Customer.getLevelId() == 2){

                                    }else if(top5Customer.getLevelId() == 3){

                                    }else if(top5Customer.getLevelId() == 4){

                                    }else if(top5Customer.getLevelId() == 5){
                                        // 判断是否直接推荐了9个明星
                                        int top5Count = customerDao.queryCustomerByLevelIdAndParentId(5, top5Customer.getId());
                                        if(top5Count > 8) {
                                            top5Customer.setLevelId(6); // 升大腕

                                            // 同步共享等级
                                            top5Customer.setLevelCopyId(6);
                                            if("0".equals(top5Customer.getIsActiveCopy())){
                                                // 是否购买过共享产品
                                                List<Orders> ordersList = ordersDao.queryOrdersByUserIdIsBuyShare(top5Customer.getId());
                                                if(ordersList.size() > 0){
                                                    top5Customer.setIsActiveCopy("1"); // 激活共享等级
                                                }
                                            }
                                            // TODO 直播等级 等待完善
                                            // 同步直播等级
                                            top5Customer.setLevelCopy1Id(6);
                                            // 判断是否购买过直播产品，买过就激活
                                            top5Customer.setIsActiveCopy1("0"); // 待激活直播等级

                                            // 同步蜜淘等级
                                            top5Customer.setLevelCopy2Id(6);
                                            if("0".equals(top5Customer.getIsActiveCopy2())){
                                                // 是否购买过蜜淘产品
                                                List<GoodsOrders> ordersList = goodsOrdersDao.queryGoodsOrdersByUserIdIsBuyBeeAmoy(top5Customer.getId());
                                                if(ordersList.size() > 0){
                                                    top5Customer.setIsActive("1"); // 激活蜜淘等级
                                                    if(top5Customer.getAddUpUpgrade().doubleValue() < 200000){
                                                        top5Customer.setAddUpUpgradeFiction(BigDecimal.valueOf(200000).subtract(top5Customer.getAddUpUpgrade()).add(top5Customer.getAddUpUpgradeFiction()));
                                                    }
                                                }
                                            }

                                            customerDao.update(top5Customer);
                                        }else{

                                        }
                                    }
                                }
                            }
                        }else{

                        }

                    }else if(parentCustomer.getLevelId() == 5){ // 明星
                        // 判断是否直接推荐了9个明星
                        int top5Count = customerDao.queryCustomerByLevelIdAndParentId(5, parentCustomer.getId());
                        if(top5Count > 8) {
                            parentCustomer.setLevelId(6); // 升大腕

                            // 同步共享等级
                            parentCustomer.setLevelCopyId(6);
                            if("0".equals(parentCustomer.getIsActiveCopy())){
                                // 是否购买过共享产品
                                List<Orders> ordersList = ordersDao.queryOrdersByUserIdIsBuyShare(parentCustomer.getId());
                                if(ordersList.size() > 0){
                                    parentCustomer.setIsActiveCopy("1"); // 激活共享等级
                                }
                            }
                            // TODO 直播等级 等待完善
                            // 同步直播等级
                            parentCustomer.setLevelCopy1Id(6);
                            // 判断是否购买过直播产品，买过就激活
                            parentCustomer.setIsActiveCopy1("0"); // 待激活直播等级

                            // 同步蜜淘等级
                            parentCustomer.setLevelCopy2Id(6);
                            if("0".equals(parentCustomer.getIsActiveCopy2())){
                                // 是否购买过蜜淘产品
                                List<GoodsOrders> ordersList = goodsOrdersDao.queryGoodsOrdersByUserIdIsBuyBeeAmoy(parentCustomer.getId());
                                if(ordersList.size() > 0){
                                    parentCustomer.setIsActive("1"); // 激活蜜淘等级
                                    if(parentCustomer.getAddUpUpgrade().doubleValue() < 200000){
                                        parentCustomer.setAddUpUpgradeFiction(BigDecimal.valueOf(200000).subtract(parentCustomer.getAddUpUpgrade()).add(parentCustomer.getAddUpUpgradeFiction()));
                                    }
                                }
                            }

                            customerDao.update(parentCustomer);
                        }else{

                        }
                    }
                }
            }
        }else if(customer.getLevelId() == 2){ // 会员

        }else if(customer.getLevelId() == 3){ // 小咖

        }else if(customer.getLevelId() == 4){ // 网红

        }else if(customer.getLevelId() == 5){ // 明星

        }else if(customer.getLevelId() == 6){ // 大腕

        }else if(customer.getLevelId() == 7){ // 公司

        }
    }


    /**
     * 判断极乐桑巴拼团是否开始
     * 早上十点至十一点、
     * 下午三点至四点、
     * 晚上八点至九点半点
     * @return
     */
    @GetMapping("/judgeCollageIsStarts")
    public ResponseServer judgeCollageIsStarts() throws ParseException {
//        SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd");
//        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
//        String time = df.format(new Date());
//
//        // 早上十点至十一点
//        String time10 = time + " 10:00:00";
//        Date date10 = sdf.parse(time10);
//
//        Calendar begin10 = Calendar.getInstance();
//        begin10.setTime(date10);
//
//        String time11 = time + " 11:00:00";
//        Date date11 = sdf.parse(time11);
//
//        Calendar end11 = Calendar.getInstance();
//        end11.setTime(date11);
//
//        // 下午三点至四点
//        String time15 = time + " 15:00:00";
//        Date date15 = sdf.parse(time15);
//
//        Calendar begin15 = Calendar.getInstance();
//        begin15.setTime(date15);
//
//        String time16 = time + " 16:00:00";
//        Date date16 = sdf.parse(time16);
//
//        Calendar end16 = Calendar.getInstance();
//        end16.setTime(date16);
//
//
//        // 晚上八点至九点半点
//        String time20 = time + " 20:00:00";
//        Date date20 = sdf.parse(time20);
//
//        Calendar begin20 = Calendar.getInstance();
//        begin20.setTime(date20);
//
//        String time21 = time + " 21:30:00";
//        Date date21 = sdf.parse(time21);
//
//        Calendar end21 = Calendar.getInstance();
//        end21.setTime(date21);
//
//        Date date = new Date(); // 系统当前时间
//
//        Calendar nowTime = Calendar.getInstance();
//        nowTime.setTime(date);

//        if( (nowTime.after(begin10) && nowTime.before(end11)) || (nowTime.after(begin15) && nowTime.before(end16))
//                || (nowTime.after(begin20) && nowTime.before(end21)) ){
//            return ResponseServer.success("可以购买");
//        }
//        return ResponseServer.error("不可以购买");
        return ResponseServer.success("可以购买");
    }


    /**
     * 签到
     * @param userId
     * @return
     */
    @GetMapping("/saveSignIn")
    public ResponseServer saveSignIn(Integer userId){
        Customer customer = customerDao.queryById(userId);
        SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd");
        String time = df.format(new Date());
        SignIn signIn = signInDao.queryByTodayIsSignIn(userId, time);
        if(signIn == null){
            SignIn newSi = new SignIn();
            newSi.setUserId(userId);
            newSi.setSignInTime(new Date());
            signInDao.save(newSi);

            // 送9个极乐值
            Account acc = accountDao.queryAccountByUserId(userId);
            acc.setBliss(acc.getBliss() + 9);
            accountDao.update(acc);
            AccountRecord ar = new AccountRecord();
            ar.setIntoUserId(userId);
            ar.setType("2");
            ar.setSign("1");
            ar.setUpdateTime(new Date());
            ar.setAmount(new BigDecimal(9));
            ar.setNowAmount(new BigDecimal(acc.getBliss()));
            ar.setInfo(customer.getAgentCode() + "签到成功! 获极乐值：" + 9);
            accountRecordDao.save(ar);

            SignInCopy signInCopy = signInCopyDao.queryByUserId(userId);
            if(signInCopy == null){
                SignInCopy copy = new SignInCopy();
                copy.setContinuity(1);
                copy.setUserId(userId);
                signInCopyDao.save(copy);
            }else{
                SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
                Date date = new Date();
                Calendar now = Calendar.getInstance();
                now.setTime(date);
                now.add(Calendar.DAY_OF_MONTH, -1);
                String date1 = sdf.format(now.getTime());
                SignIn signIn_1 = signInDao.queryByTodayIsSignIn(userId, date1);
                if(signIn_1 == null){
                    signInCopy.setContinuity(1);
                }else{
                    signInCopy.setContinuity(signInCopy.getContinuity() + 1);
                }
                signInCopyDao.update(signInCopy);
            }
            return ResponseServer.success();
        }else{
            return ResponseServer.error("今日已签到");
        }
    }


    /**
     * 加载签到页面
     * @param userId
     * @return
     */
    @GetMapping("/getSignIn")
    public ResponseServer getSignIn(Integer userId){
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        Map map = new HashMap();
        map.put("sumCount", signInDao.queryByUserId(userId).size());
        SignInCopy copy = signInCopyDao.queryByUserId(userId);
        if(copy == null){
            map.put("continuity", 0);
        }else{
            //Date date = new Date();
            //Calendar now = Calendar.getInstance();
            //now.setTime(date);
            //now.add(Calendar.DAY_OF_MONTH, -1);
            //String date1 = sdf.format(now.getTime());
            //SignIn signIn_1 = signInDao.queryByTodayIsSignIn(userId, date1);
            //if(signIn_1 == null){
                //String time = sdf.format(new Date());
                //SignIn signIn = signInDao.queryByTodayIsSignIn(userId, time);
                //if(signIn == null){
                    //map.put("continuity", 0);
                //}else{
                    //map.put("continuity", 1);
                //}
            //}else{
                map.put("continuity", copy.getContinuity());
            //}
        }
        // 判断今日是否签到成功
        String time = sdf.format(new Date());
        SignIn signIn = signInDao.queryByTodayIsSignIn(userId, time);
        if(signIn == null){
            map.put("today", 0);
        }else{
            map.put("today", 1);
        }
        return ResponseServer.success(map);
    }


    /**
     * 获取团信息
     * @param modeProductId
     * @return
     */
    @GetMapping("/getCollageInfo")
    public ResponseServer getCollageInfo(Integer modeProductId){
        Map map = new HashMap();
        ModeProduct mp = modeProductDao.queryById(modeProductId);
        CollageMode cm = collageModeDao.queryById(mp.getModeId());
        map.put("maxGroupNum", cm.getPeopleQuantity());
        List<CollageUser> cuList = collageUserDao.queryByModeProductId(mp.getId());
        List<String> list = new ArrayList();
        if(cuList.size() > 0){
            for(CollageUser cu : cuList) {
                list.add(customerDao.queryById(cu.getUserId()).getHeadImg());
            }
        }
        map.put("headImgList", list);
        map.put("modeImg", cm.getImg());
        return ResponseServer.success(map);
    }


    /**
     * 判断当前登录用户是否有编号
     * @param userId
     * @return
     */
    @GetMapping("/judgeAgentCode")
    public ResponseServer judgeAgentCode(Integer userId){
        Customer customer = customerDao.queryById(userId);
        return ResponseServer.success(customer);
    }


    /**
     * 判断是否可以参与此团
     * @param userId
     * @param productId
     * @return
     */
    @GetMapping("/judgeJoinCollage")
    public ResponseServer judgeJoinCollage(Integer userId, Integer productId){
        // 正在进行中的团
        ModeProduct modeProduct = modeProductDao.queryByProductIdByStatus(productId);
        if(modeProduct != null){
            Orders isO = ordersDao.queryByIsO(userId, modeProduct.getId());
            if(isO != null){
                return ResponseServer.error("当前拼团您已参与!!! 敬请期待下一个拼团");
            }
        }
        // 团成功，勾选了拼中为止的人,在挪团时
        Orders o = ordersDao.queryByCondition(userId, productId);
        if(o != null){
            OrdersCopy oc = ordersCopyDao.queryOCByOrderNo(o.getOrderNo());
            if(oc != null){
                return ResponseServer.error("当前拼团您已参与!!! 您已勾选拼中为止");
            }
        }
        return ResponseServer.success("可以参与");
    }


    /**
     * 红包排行榜
     * 当日有10个就取当日所有
     * 当日没有10个就取最新10个
     * @return
     */
    @GetMapping("/rankingData")
    public ResponseServer rankingData(){
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        String date = sdf.format(new Date());
        List<OpenRedPackDTO> orpList = openRedPackDao.queryBy369Today(date);
        if(orpList.size() >= 10){
            return ResponseServer.success(orpList);
        }else{
            List<OpenRedPackDTO> openList = openRedPackDao.queryBy369Limit();
            return ResponseServer.success(openList);
        }
    }


    /**
     * 中1980旅游
     * 最新20条数据
     * @return
     */
    @GetMapping("/prize1980Data")
    public ResponseServer prize1980Data(){
        List<OrdersVO> ordersList = ordersDao.queryBy1980Limit();
        return ResponseServer.success(ordersList);
    }


    /**
     * 个人的银行卡信息
     * @param userId
     * @return
     */
    @GetMapping("/userCardData")
    public ResponseServer userCardData(Integer userId){
        List<UserCardDTO> dtoList = userCardDao.queryByUserId(userId);
        if(dtoList.size() > 0){
            for(int i = 0; i < dtoList.size(); i++){
                UserCardDTO dto = dtoList.get(i);
                if(i == 0){
                    dto.setSelected(1);
                }else{
                    dto.setSelected(0);
                }
            }
        }
        return ResponseServer.success(dtoList);
    }


    /**
     * 保存个人的银行卡信息
     * @param userId
     * @param name
     * @param cardType
     * @param phoneNumber
     * @param bankName
     * @param bankNumber
     * @return
     */
    @PostMapping("/userCardSave")
    public ResponseServer userCardSave(Integer userId, String name, String cardType, String phoneNumber, String bankName, String bankNumber){
        UserCard uc = userCardDao.queryByBankNumber(bankNumber);
        if(uc == null){
            UserCard userCard = new UserCard();
            userCard.setUserId(userId);
            userCard.setHolder(name);
            userCard.setBankName(cardType);
            userCard.setCardNumber(bankNumber);
            userCard.setPhone(phoneNumber);
            userCard.setTypeName(bankName);
            userCard.setUpdateTime(new Date());
            userCardDao.save(userCard);
            return ResponseServer.success();
        }else{
            return ResponseServer.error("该银行卡已存在!");
        }
    }


    /**
     * 删除个人的银行卡信息
     * @param cardId
     * @return
     */
    @PostMapping("/userCardDelete")
    public ResponseServer userCardDelete(Integer cardId){
        userCardDao.delete(cardId);
        return ResponseServer.success();
    }


    /**
     * 个人余额提现
     * @param userId
     * @param cardId
     * @param amount
     * @return
     */
    @PostMapping("/cardWithdrawalData")
    public ResponseServer cardWithdrawalData(Integer userId, Integer cardId, BigDecimal amount){
        if(amount == null){
            return ResponseServer.error("提现金额需大于等于100元");
        }else{
            if(amount.doubleValue() < 100){
                return ResponseServer.error("提现金额需大于等于100元");
            }else{
                if(amount.doubleValue() % 100 != 0){
                    return ResponseServer.error("提现金额需为100的倍数");
                }
            }
        }
        Customer customer = customerDao.queryById(userId);
        if(customer == null){
            return ResponseServer.error("当前用户信息不正确");
        }
        Account account = accountDao.queryAccountByUserId(userId);
        if(account.getVoucherBalance().doubleValue() < amount.doubleValue()){
            return ResponseServer.error("余额不足");
        }
        UserCard userCard = userCardDao.queryById(cardId);
        if(userCard == null){
            return ResponseServer.error("请选择银行卡");
        }

        BigDecimal bigD = null;
        if(amount.doubleValue() <= 5000){
            bigD = new BigDecimal(0.03); // 5000以下
        }else if(amount.doubleValue() > 5000){
            bigD = new BigDecimal(0.02); // 5000以上
        }

        BigDecimal deduction = amount.multiply(bigD); // 扣除的手续费
        BigDecimal remain = amount.subtract(deduction); // 实际到账的钱


        account.setVoucherBalance(account.getVoucherBalance().subtract(amount));
        accountDao.update(account);

        // 提现订单号
        String orderNo = "TXH" + Units.getOrderIdByTime().replaceAll("-", "");

        AccountRecord ar = new AccountRecord();
        ar.setIntoUserId(userId);
        ar.setUpdateTime(new Date());
        ar.setType("0");
        ar.setAmount(amount);
        ar.setNowAmount(account.getVoucherBalance());
        ar.setSign("2");
        ar.setInfo(customer.getAgentCode() + "提现金额为：" + amount);
        ar.setOrderNo(orderNo);
        accountRecordDao.save(ar);

        CardWithdrawal cw = new CardWithdrawal();
        cw.setOrderNo(orderNo);
        cw.setAmount(amount);
        cw.setChargeFee(bigD);
        cw.setNowAmount(remain);
        cw.setUserId(userId);
        cw.setUserCardId(cardId);
        cw.setStatus("0");
        cw.setCreateTime(new Date());
        cw.setBankName(userCard.getBankName());
        cw.setTypeName(userCard.getTypeName());
        cw.setCardNumber(userCard.getTypeName() + "：" + userCard.getCardNumber());
        cw.setHolder(userCard.getHolder());
        cw.setPhone(userCard.getPhone());
        cw.setAccountRecordId(ar.getId());
        cw.setIdCard(customer.getIdCard() + " : ");
        int row = cardWithdrawalDao.save(cw);
        if(row > 0){
            return ResponseServer.success("提现成功");
        }
        return ResponseServer.error("提现失败");
    }


    /**
     * 加载中秋产品
     * @return
     */
    @GetMapping("/getAutumnProduct")
    public ResponseServer getAutumnProduct(){
        List<Product> voList = productDao.queryAutumnProduct();
        return ResponseServer.success("加载成功", voList);
    }


    /**
     * 加载七夕产品
     * @param classifyId
     * @return
     */
    @GetMapping("/getQiXiData_product")
    public ResponseServer getQiXiData_product(Integer classifyId){
        List<Product> voList = productDao.queryQiXiProduct(classifyId);
        return ResponseServer.success("加载成功", voList);
    }


    /**
     * 买过七夕产品的人
     * 最新20条数据
     * @return
     */
    @GetMapping("/prizeQiXiData")
    public ResponseServer prizeQiXiData(){
        List<OrdersVO> ordersList = ordersDao.queryByQiXiLimit();
        return ResponseServer.success(ordersList);
    }


    /**
     * 七夕活动是否上架
     * @return
     */
    @GetMapping("/judgeQiXi")
    public ResponseServer judgeQiXi(){
        Activity activity = activityDao.queryById(1);
        return ResponseServer.success(activity);
    }


    /**
     * 拼团是否上架
     * @return
     */
    @GetMapping("/judgeCollage")
    public ResponseServer judgeCollage(){
        Activity activity = activityDao.queryById(3);
        return ResponseServer.success(activity);
    }


    /**
     * 速度与激情是否上架
     * @return
     */
    @GetMapping("/judgeSpeedPassion")
    public ResponseServer judgeSpeedPassion(){
        Activity activity = activityDao.queryById(4);
        return ResponseServer.success(activity);
    }


    /**
     * 盲盒是否上架
     * @return
     */
    @GetMapping("/judgeBox")
    public ResponseServer judgeBox(){
        Activity activity = activityDao.queryById(2);
        return ResponseServer.success(activity);
    }


    /**
     * 购买七夕产品，微信支付
     * @param request
     * @param modeId
     * @param openId
     * @param consigneeName
     * @param fullAddress
     * @param consigneePhone
     * @param userId
     * @param freight
     * @return
     */
    @PostMapping("/qiXi/pay")
    public ResponseServer qiXiPay(HttpServletRequest request, @RequestParam(required = false) Integer modeId,
                                      @RequestParam(required = false) String openId,
                                      @RequestParam(required = false) String consigneeName,
                                      @RequestParam(required = false) String fullAddress,
                                      @RequestParam(required = false) String consigneePhone,
                                      @RequestParam(required = false) Integer userId,
                                      @RequestParam(required = false) BigDecimal freight) throws Exception {

        System.err.println("-------------创建订单传递的参数：modeId= " + modeId);
        System.err.println("-------------创建订单传递的参数：openId= " + openId);
        System.err.println("-------------创建订单传递的参数：consigneeName= " + consigneeName);
        System.err.println("-------------创建订单传递的参数：fullAddress= " + fullAddress);
        System.err.println("-------------创建订单传递的参数：consigneePhone= " + consigneePhone);
        System.err.println("-------------创建订单传递的参数：userId= " + userId);
        System.err.println("-------------创建订单传递的参数：freight= " + freight);

        Map<String, String> maps = new HashMap<>();
        CollageMode collageMode = collageModeDao.queryById(modeId);
        BigDecimal totalPrice;
        // 商户订单号
        String outTradeNo = "BEE" + Units.getOrderIdByTime().replaceAll("-", "");
        // 交易号
        String tradeNo = "JYH" + Units.getOrderIdByTime().replaceAll("-", "");
        if (freight == null) {
            freight = BigDecimal.valueOf(0.0);
        }
        // 随机产品
        List<Product> productList = productDao.queryProductByClassifyId(modeId);
        int productSize = productList.size();
        int productRandom = 1 + (int)(Math.random()*(productSize + 1 - 1));
        Product product = productList.get(productRandom-1);
        //List<SkuRelation> skuList = skuRelationDao.queryByProductId(product.getId());
        //SkuRelation sku = skuList.get(0);
        BigDecimal bd = new BigDecimal(299); // 七夕产品统一支付 299 即可购买
        totalPrice = bd.add(freight);
        Map<String, String> map;
        if (totalPrice.doubleValue() > 0) {
            Map<String, Object> wxPay = new HashMap<>();
            wxPay.put("totalPrice", totalPrice.doubleValue());
            wxPay.put("outTradeNo", outTradeNo);
            wxPay.put("openId", openId);
            wxPay.put("notifyUrl", Constants.notify_url_qixi);
            wxPay.put("wxPayAppId", Constants.wxAppId);
            wxPay.put("tradeType", Constants.trade_type);
            String paramBuffer = CreateUnifiedOrder.UnifiedOrder(request, wxPay);
            map = Units.doXMLParse(HttpRequestUtil.sendPost(Constants.pay_url, new String(paramBuffer.getBytes(), "UTF-8")));
            // 创建订单
            if (map != null) {
                Orders orders = new Orders();
                orders.setOrderNo(outTradeNo);
                orders.setTradeNo(tradeNo);
                orders.setTotalAmount(totalPrice);
                orders.setPayAmount(totalPrice);
                orders.setCouponAmount(new BigDecimal(0));
                orders.setFreight(freight);
                orders.setPayStatus("0");
                orders.setPayType("0");
                orders.setDealStatus("0");
                orders.setRefundStatus("0");
                orders.setPrepayId(map.get("prepay_id"));
                orders.setOrderPersonId(userId);
                orders.setConsigneeName(consigneeName);
                orders.setConsigneePhone(consigneePhone);
                orders.setAddress(fullAddress);
                orders.setUpdateTime(new Date());
                orders.setIsDel("1");
                orders.setIsRun("0");
                orders.setLastCollage("0");
                orders.setRemarks("七夕订单");
                orders.setQixiToId(modeId);
                orders.setProductId(product.getId());
                ordersDao.save(orders);
                maps.put("prepayId", map.get("prepay_id"));
                maps.put("outTradeNo", outTradeNo);
                return ResponseServer.success(maps);
            }
        }
        maps.put("prepayId", "");
        maps.put("msg", "支付失败,请重试");
        return ResponseServer.success(maps);
    }


    /**
     * 七夕产品支付成功后回调
     * @param request
     * @param response
     */
    @PostMapping("/notify_url_qixi")
    public void qiXiPayCallback(HttpServletRequest request, HttpServletResponse response) {
        System.err.println("微信回调接口方法 start ----------------------------");
        String inputLine = "";
        String notityXml = "";
        try {
            while ((inputLine = request.getReader().readLine()) != null) {
                notityXml += inputLine;
            }
            // 关闭流
            request.getReader().close();
            System.err.println("小程序商城支付回调：" + notityXml);
            // 解析成Map
            Map<String, String> map = Units.doXMLParse(notityXml);
            System.err.println(map);
            // 判断 支付是否成功
            if ("SUCCESS".equals(map.get("result_code"))) {
                System.err.println("微信回调返回是否支付成功：是");
                // 获得 返回的商户订单号
                String outTradeNo = map.get("out_trade_no");
                double totalFee = Double.parseDouble(map.get("total_fee")) / 100;
                System.err.println("微信回调返回商户订单号：" + outTradeNo);
                System.err.println("微信回调返回支付金额：" + totalFee);

                Orders orders = ordersDao.queryByOrderNo(outTradeNo);

                Product product = productDao.queryById(orders.getProductId());
                product.setSales(product.getSales() + 1); // 添加销量
                productDao.update(product);

                OrderDetails od = new OrderDetails();
                od.setOrderNo(orders.getOrderNo());
                od.setTradeNo(orders.getTradeNo());
                od.setStoreShopId(product.getStoreShopId());
                od.setStoreShopName(storeShopDao.queryById(product.getStoreShopId()).getName());
                od.setClassifyId(product.getClassifyId());
                od.setClassifyName(classifyDao.queryById(product.getClassifyId()).getName());
                od.setProductId(product.getId());
                od.setProductType(product.getType());
                od.setProductImg(product.getImg());
                od.setProductName(product.getName());
                List<SkuRelation> skuList = skuRelationDao.queryByProductId(product.getId());
                SkuRelation sku = skuList.get(0);
                od.setProductCode(product.getProductCode());
                od.setCostPrice(sku.getCostPrice());
                od.setRelationId(sku.getId());
                if(sku.getGroupRelation().contains(",")){
                    String[] strings = sku.getGroupRelation().split(",");
                    String str = "";
                    for(int u = 0; u < strings.length; u++){
                        str += specAttributeDao.queryById(Integer.parseInt(strings[u])).getAttributeName() + "，";
                    }
                    od.setSpecAttributeName(str.substring(0, str.length()-1));
                }else{
                    od.setSpecAttributeName(specAttributeDao.queryById(Integer.parseInt(sku.getGroupRelation())).getAttributeName());
                }
                od.setQuantity(1);
                od.setUnitPrice(sku.getRetailPrice());
                od.setUpdateTime(new Date());
                orderDetailsDao.save(od);
                // 修改订单状态
                orders.setPayStatus("1");
                orders.setDealStatus("1");
                orders.setIsDel("0");
                ordersDao.update(orders);

                // 封装 返回值
                StringBuffer buffer = new StringBuffer();
                buffer.append("<xml>");
                buffer.append("<return_code>SUCCESS</return_code>");
                buffer.append("<return_msg>OK</return_msg>");
                buffer.append("</xml>");
                // 给微信服务器返回 成功标示 否则会一直询问服务器是否回调成功
                PrintWriter writer = response.getWriter();
                // 返回
                writer.print(buffer.toString());
            }
        } catch (IOException e) {
            e.printStackTrace();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }


    /**
     * 加载积分产品数据
     * @return
     */
    @GetMapping("/getPointsProductData")
    public ResponseServer getPointsProductData(){
        List<ProductVO> voList = productDao.queryProductByPoints();
        return ResponseServer.success("加载成功", voList);
    }


    /**
     * 积分商城加载头像和积分
     * @return
     */
    @GetMapping("/getPointsAndHeadImg")
    public ResponseServer getPointsAndHeadImg(Integer userId){
        Customer customer = customerDao.queryById(userId);
        Account account = accountDao.queryAccountByUserId(customer.getId());
        Map map = new HashMap();
        map.put("headImg", customer.getHeadImg());
        map.put("integral", account.getIntegral());
        return ResponseServer.success("加载成功", map);
    }


    /**
     * 积分兑换，微信支付
     * @param request
     * @param productId
     * @param openId
     * @param consigneeName
     * @param fullAddress
     * @param consigneePhone
     * @param userId
     * @param freight
     * @return
     */
    @PostMapping("/integral/pay")
    public ResponseServer integralPay(HttpServletRequest request, @RequestParam(required = false) Integer productId,
                                    @RequestParam(required = false) String openId,
                                    @RequestParam(required = false) String consigneeName,
                                    @RequestParam(required = false) String fullAddress,
                                    @RequestParam(required = false) String consigneePhone,
                                    @RequestParam(required = false) Integer userId,
                                    @RequestParam(required = false) BigDecimal freight) throws Exception {

        System.err.println("-------------创建订单传递的参数：productId= " + productId);
        System.err.println("-------------创建订单传递的参数：openId= " + openId);
        System.err.println("-------------创建订单传递的参数：consigneeName= " + consigneeName);
        System.err.println("-------------创建订单传递的参数：fullAddress= " + fullAddress);
        System.err.println("-------------创建订单传递的参数：consigneePhone= " + consigneePhone);
        System.err.println("-------------创建订单传递的参数：userId= " + userId);
        System.err.println("-------------创建订单传递的参数：freight= " + freight);

        Map<String, String> maps = new HashMap<>();

        Product product = productDao.queryById(productId);
        if(product == null){
            maps.put("prepayId", "");
            maps.put("msg", "支付失败,产品信息错误");
            return ResponseServer.success(maps);
        }
        Customer customer = customerDao.queryById(userId);
        Account account = accountDao.queryAccountByUserId(customer.getId());
        if(account.getIntegral() < product.getRedeemPoints()){
            maps.put("prepayId", "");
            maps.put("msg", "支付失败,积分不足");
            return ResponseServer.success(maps);
        }
        BigDecimal totalPrice; // 需要支付的金额
        // 商户订单号
        String outTradeNo = "BEE" + Units.getOrderIdByTime().replaceAll("-", "");
        // 交易号
        String tradeNo = "JYH" + Units.getOrderIdByTime().replaceAll("-", "");
        if (freight == null) {
            freight = BigDecimal.valueOf(0.0);
        }
        List<SkuRelation> skuList = skuRelationDao.queryByProductId(productId);
        SkuRelation sku = skuList.get(0);
        BigDecimal totalAmount = sku.getRetailPrice(); // 总金额
        totalPrice = sku.getRetailPrice().add(freight);
        Map<String, String> map;
        if (totalPrice.doubleValue() > 0) {
            Map<String, Object> wxPay = new HashMap<>();
            wxPay.put("totalPrice", totalPrice.doubleValue());
            wxPay.put("outTradeNo", outTradeNo);
            wxPay.put("openId", openId);
            wxPay.put("notifyUrl", Constants.notify_url_integral);
            wxPay.put("wxPayAppId", Constants.wxAppId);
            wxPay.put("tradeType", Constants.trade_type);
            String paramBuffer = CreateUnifiedOrder.UnifiedOrder(request, wxPay);
            map = Units.doXMLParse(HttpRequestUtil.sendPost(Constants.pay_url, new String(paramBuffer.getBytes(), "UTF-8")));
            // 创建订单
            if (map != null) {
                Orders orders = new Orders();
                orders.setOrderNo(outTradeNo);
                orders.setTradeNo(tradeNo);
                orders.setTotalAmount(totalAmount); // 总金额
                orders.setPayAmount(totalPrice);  // 实际支付金额
                orders.setCouponAmount(new BigDecimal(0));  // 优惠券抵扣金额
                orders.setFreight(freight); // 运费金额
                orders.setPayStatus("0");
                orders.setPayType("0");
                orders.setDealStatus("0");
                orders.setRefundStatus("0");
                orders.setPrepayId(map.get("prepay_id"));
                orders.setOrderPersonId(userId);
                orders.setConsigneeName(consigneeName);
                orders.setConsigneePhone(consigneePhone);
                orders.setAddress(fullAddress);
                orders.setUpdateTime(new Date());
                orders.setIsDel("0");
                orders.setIsRun("0");
                orders.setRemarks("积分兑换订单");
                orders.setProductId(product.getId());
                ordersDao.save(orders);

                OrderDetails od = new OrderDetails();
                od.setOrderNo(orders.getOrderNo());
                od.setTradeNo(orders.getTradeNo());
                od.setStoreShopId(product.getStoreShopId());
                od.setStoreShopName(storeShopDao.queryById(product.getStoreShopId()).getName());
                od.setClassifyId(product.getClassifyId());
                od.setClassifyName(classifyDao.queryById(product.getClassifyId()).getName());
                od.setProductId(product.getId());
                od.setProductType(product.getType());
                od.setProductImg(product.getImg());
                od.setProductName(product.getName());

                od.setProductCode(product.getProductCode());
                od.setCostPrice(sku.getCostPrice());
                od.setRelationId(sku.getId());
                if(sku.getGroupRelation().contains(",")){
                    String[] strings = sku.getGroupRelation().split(",");
                    String str = "";
                    for(int u = 0; u < strings.length; u++){
                        str += specAttributeDao.queryById(Integer.parseInt(strings[u])).getAttributeName() + "，";
                    }
                    od.setSpecAttributeName(str.substring(0, str.length()-1));
                }else{
                    od.setSpecAttributeName(specAttributeDao.queryById(Integer.parseInt(sku.getGroupRelation())).getAttributeName());
                }
                od.setQuantity(1);
                od.setUnitPrice(sku.getRetailPrice());
                od.setUpdateTime(new Date());
                od.setUseIntegral(product.getRedeemPoints());
                orderDetailsDao.save(od);

                maps.put("prepayId", map.get("prepay_id"));
                maps.put("outTradeNo", outTradeNo);
                return ResponseServer.success(maps);
            }
        }
        maps.put("prepayId", "");
        maps.put("msg", "支付失败,请重试");
        return ResponseServer.success(maps);
    }


    /**
     * 积分兑换支付成功后回调
     * @param request
     * @param response
     */
    @PostMapping("/notify_url_integral")
    public void integralPayCallback(HttpServletRequest request, HttpServletResponse response) {
        System.err.println("微信回调接口方法 start ----------------------------");
        String inputLine = "";
        String notityXml = "";
        try {
            while ((inputLine = request.getReader().readLine()) != null) {
                notityXml += inputLine;
            }
            // 关闭流
            request.getReader().close();
            System.err.println("小程序商城支付回调：" + notityXml);
            // 解析成Map
            Map<String, String> map = Units.doXMLParse(notityXml);
            System.err.println(map);
            // 判断 支付是否成功
            if ("SUCCESS".equals(map.get("result_code"))) {
                System.err.println("微信回调返回是否支付成功：是");
                // 获得 返回的商户订单号
                String outTradeNo = map.get("out_trade_no");
                double totalFee = Double.parseDouble(map.get("total_fee")) / 100;
                System.err.println("微信回调返回商户订单号：" + outTradeNo);
                System.err.println("微信回调返回支付金额：" + totalFee);

                Orders orders = ordersDao.queryByOrderNo(outTradeNo);

                // 修改订单状态
                orders.setPayStatus("1");
                orders.setDealStatus("1");
                orders.setIsDel("0");
                ordersDao.update(orders);

                Product product = productDao.queryById(orders.getProductId());
                product.setSales(product.getSales() + 1); // 添加销量
                productDao.update(product);

                Customer customer = customerDao.queryById(orders.getOrderPersonId());

                Account acc = accountDao.queryAccountByUserId(customer.getId());
                acc.setIntegral(acc.getIntegral() - product.getRedeemPoints());
                accountDao.update(acc);

                AccountRecord ar0 = new AccountRecord();
                ar0.setOutUserId(customer.getId());
                ar0.setUpdateTime(new Date());
                ar0.setType("1");
                ar0.setAmount(BigDecimal.valueOf(product.getRedeemPoints()));
                ar0.setNowAmount(BigDecimal.valueOf(acc.getIntegral()));
                ar0.setSign("2");
                ar0.setOrderNo(outTradeNo);
                ar0.setInfo(customerDao.queryById(orders.getOrderPersonId()).getAgentCode() + "购买成功! 消耗积分：" + product.getRedeemPoints());
                accountRecordDao.save(ar0);

                int give = (int)Math.round(orders.getPayAmount().doubleValue());
                acc.setIntegral(acc.getIntegral() + give);
                accountDao.update(acc);

                AccountRecord ar = new AccountRecord();
                ar.setIntoUserId(customer.getId());
                ar.setUpdateTime(new Date());
                ar.setType("1");
                ar.setAmount(BigDecimal.valueOf(give));
                ar.setNowAmount(BigDecimal.valueOf(acc.getIntegral()));
                ar.setSign("1");
                ar.setOrderNo(outTradeNo);
                ar.setInfo(customerDao.queryById(orders.getOrderPersonId()).getAgentCode() + "购买成功! 您获得积分：" + give);
                accountRecordDao.save(ar);

                // 封装 返回值
                StringBuffer buffer = new StringBuffer();
                buffer.append("<xml>");
                buffer.append("<return_code>SUCCESS</return_code>");
                buffer.append("<return_msg>OK</return_msg>");
                buffer.append("</xml>");
                // 给微信服务器返回 成功标示 否则会一直询问服务器是否回调成功
                PrintWriter writer = response.getWriter();
                // 返回
                writer.print(buffer.toString());
            }
        } catch (IOException e) {
            e.printStackTrace();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }


    /**
     * 积分兑换，余额支付
     * @param productId
     * @param openId
     * @param consigneeName
     * @param fullAddress
     * @param consigneePhone
     * @param userId
     * @param freight
     * @return
     */
    @PostMapping("/integral/pay/voucher")
    public ResponseServer integralPayVoucher(@RequestParam(required = false) Integer productId,
                                           @RequestParam(required = false) String openId,
                                           @RequestParam(required = false) String consigneeName,
                                           @RequestParam(required = false) String fullAddress,
                                           @RequestParam(required = false) String consigneePhone,
                                           @RequestParam(required = false) Integer userId,
                                           @RequestParam(required = false) BigDecimal freight){

        System.err.println("-------------创建订单传递的参数：productId= " + productId);
        System.err.println("-------------创建订单传递的参数：openId= " + openId);
        System.err.println("-------------创建订单传递的参数：consigneeName= " + consigneeName);
        System.err.println("-------------创建订单传递的参数：fullAddress= " + fullAddress);
        System.err.println("-------------创建订单传递的参数：consigneePhone= " + consigneePhone);
        System.err.println("-------------创建订单传递的参数：userId= " + userId);
        System.err.println("-------------创建订单传递的参数：freight= " + freight);

        Product product = productDao.queryById(productId);
        if(product == null){
            return ResponseServer.error("支付失败,产品信息错误");
        }
        Customer customer = customerDao.queryById(userId);
        if(customer == null){
            return ResponseServer.error("支付失败,用户信息不正确，请重新授权");
        }

        BigDecimal totalPrice; // 实际支付的钱
        // 商户订单号
        String outTradeNo = "BEE" + Units.getOrderIdByTime().replaceAll("-", "");
        // 交易号
        String tradeNo = "JYH" + Units.getOrderIdByTime().replaceAll("-", "");
        if (freight == null) {
            freight = BigDecimal.valueOf(0.0);
        }
        List<SkuRelation> skuList = skuRelationDao.queryByProductId(productId);
        SkuRelation sku = skuList.get(0);
        BigDecimal totalAmount = sku.getRetailPrice(); // 产品总金额
        totalPrice = sku.getRetailPrice().add(freight);
        Account account = accountDao.queryAccountByUserId(userId);
        if(account.getIntegral() < product.getRedeemPoints()){
            return ResponseServer.error("支付失败,积分不足");
        }
        if(account.getVoucherBalance().doubleValue() < totalPrice.doubleValue()){
            return ResponseServer.error("支付失败,余额不足");
        }
        account.setVoucherBalance(account.getVoucherBalance().subtract(totalPrice));
        account.setIntegral(account.getIntegral() - product.getRedeemPoints());
        accountDao.update(account);

        AccountRecord ar0 = new AccountRecord();
        ar0.setOutUserId(customer.getId());
        ar0.setUpdateTime(new Date());
        ar0.setType("1");
        ar0.setAmount(BigDecimal.valueOf(product.getRedeemPoints()));
        ar0.setNowAmount(BigDecimal.valueOf(account.getIntegral()));
        ar0.setSign("2");
        ar0.setOrderNo(outTradeNo);
        ar0.setInfo(customer.getAgentCode() + "购买成功! 消耗积分：" + product.getRedeemPoints());
        accountRecordDao.save(ar0);

        AccountRecord ar = new AccountRecord();
        ar.setOutUserId(userId);
        ar.setUpdateTime(new Date());
        ar.setType("0");
        ar.setAmount(totalPrice);
        ar.setNowAmount(account.getVoucherBalance());
        ar.setSign("2");
        ar.setOrderNo(outTradeNo);
        ar.setInfo(customer.getAgentCode() + "购买成功! 消费余额：" + totalPrice);
        accountRecordDao.save(ar);

        int give = (int)Math.round(totalPrice.doubleValue());
        account.setIntegral(account.getIntegral() + give);
        accountDao.update(account);

        AccountRecord ar1 = new AccountRecord();
        ar1.setIntoUserId(customer.getId());
        ar1.setUpdateTime(new Date());
        ar1.setType("1");
        ar1.setAmount(BigDecimal.valueOf(give));
        ar1.setNowAmount(BigDecimal.valueOf(account.getIntegral()));
        ar1.setSign("1");
        ar1.setOrderNo(outTradeNo);
        ar1.setInfo(customer.getAgentCode() + "购买成功! 您获得积分：" + give);
        accountRecordDao.save(ar1);

        // 创建订单
        Orders orders = new Orders();
        orders.setOrderNo(outTradeNo);
        orders.setTradeNo(tradeNo);
        orders.setTotalAmount(totalAmount); // 总金额
        orders.setPayAmount(totalPrice);  // 实际支付金额
        orders.setCouponAmount(new BigDecimal(0));  // 优惠券抵扣金额
        orders.setFreight(freight); // 运费金额
        orders.setPayStatus("1");
        orders.setPayType("1");
        orders.setDealStatus("1");
        orders.setRefundStatus("0");
        orders.setOrderPersonId(userId);
        orders.setConsigneeName(consigneeName);
        orders.setConsigneePhone(consigneePhone);
        orders.setAddress(fullAddress);
        orders.setUpdateTime(new Date());
        orders.setIsDel("0");
        orders.setIsRun("0");
        orders.setRemarks("积分兑换订单");
        orders.setProductId(product.getId());
        ordersDao.save(orders);

        OrderDetails od = new OrderDetails();
        od.setOrderNo(orders.getOrderNo());
        od.setTradeNo(orders.getTradeNo());
        od.setStoreShopId(product.getStoreShopId());
        od.setStoreShopName(storeShopDao.queryById(product.getStoreShopId()).getName());
        od.setClassifyId(product.getClassifyId());
        od.setClassifyName(classifyDao.queryById(product.getClassifyId()).getName());
        od.setProductId(product.getId());
        od.setProductType(product.getType());
        od.setProductImg(product.getImg());
        od.setProductName(product.getName());
        od.setProductCode(product.getProductCode());
        od.setCostPrice(sku.getCostPrice());
        od.setRelationId(sku.getId());
        if(sku.getGroupRelation().contains(",")){
            String[] strings = sku.getGroupRelation().split(",");
            String str = "";
            for(int u = 0; u < strings.length; u++){
                str += specAttributeDao.queryById(Integer.parseInt(strings[u])).getAttributeName() + "，";
            }
            od.setSpecAttributeName(str.substring(0, str.length()-1));
        }else{
            od.setSpecAttributeName(specAttributeDao.queryById(Integer.parseInt(sku.getGroupRelation())).getAttributeName());
        }
        od.setQuantity(1);
        od.setUnitPrice(sku.getRetailPrice());
        od.setUpdateTime(new Date());
        od.setUseIntegral(product.getRedeemPoints());
        orderDetailsDao.save(od);

        // 添加销量
        product.setSales(product.getSales() + 1);
        productDao.update(product);

        return ResponseServer.success("余额支付成功!!!");
    }


    /**
     * 积分兑换判断积分是否足够
     * @param productId
     * @param userId
     * @return
     */
    @GetMapping("/getJudgeIntegral")
    public ResponseServer getJudgeIntegral(Integer productId, Integer userId){
        Product product = productDao.queryById(productId);
        Account account = accountDao.queryAccountByUserId(userId);
        if(account.getIntegral() < product.getRedeemPoints()){
            return ResponseServer.error("积分不足!!!");
        }else{
            return ResponseServer.success("满足");
        }
    }


    /**
     * 加载公告文章信息
     * @return
     */
    @GetMapping("/getArticle")
    public ResponseServer getArticle(){
        List<Article> articleList = articleDao.queryAll();
        return ResponseServer.success("加载成功", articleList);
    }


    /**
     * 加载公告文章信息
     * @param articleId
     * @return
     */
    @GetMapping("/getArticleDetails")
    public ResponseServer getArticleDetails(Integer articleId){
        Article article = articleDao.queryById(articleId);
        return ResponseServer.success("加载成功", article);
    }


    /**
     * 加载首页banner图
     * @return
     */
    @GetMapping("/getPageHomeBanners")
    public ResponseServer getPageHomeBanners(){
        List<Banners> bannersList = bannersDao.queryBannersByType("0");
        return ResponseServer.success("加载成功", bannersList);
    }


    /**
     * 加载我的等级信息
     * @return
     */
    @GetMapping("/getMyLevelInfo")
    public ResponseServer getMyLevelInfo(Integer userId){
        Map map = new HashMap();
        List<MyLevelDTO> dtoList = new ArrayList<>();
        Customer customer = customerDao.queryById(userId);
        map.put("nickName", customer.getNickName());
        map.put("headImg", customer.getHeadImg());
        map.put("agentCode", customer.getAgentCode());
        MyLevelDTO dto = new MyLevelDTO();
        dto.setGradeName(levelCopyDao.queryById(customer.getLevelCopyId()).getName());
        dto.setTitle("拼团等级");
        dto.setIs_active(customer.getIsActiveCopy());
        dtoList.add(dto);

        MyLevelDTO dto1 = new MyLevelDTO();
        dto1.setGradeName(levelDao.queryById(customer.getLevelId()).getName());
        dto1.setTitle("共享等级");
        dto1.setIs_active(customer.getIsActive());
        dtoList.add(dto1);

        MyLevelDTO dto2 = new MyLevelDTO();
        dto2.setGradeName(levelCopy1Dao.queryById(customer.getLevelCopy1Id()).getName());
        dto2.setTitle("直播等级");
        dto2.setIs_active(customer.getIsActiveCopy1());
        dtoList.add(dto2);

        MyLevelDTO dto3 = new MyLevelDTO();
        dto3.setGradeName(levelCopy2Dao.queryById(customer.getLevelCopy2Id()).getName());
        dto3.setTitle("蜜淘等级");
        dto3.setIs_active(customer.getIsActiveCopy2());
        dtoList.add(dto3);
        map.put("levelList", dtoList);
        return ResponseServer.success(map);
    }


    // TODO 蜜淘商城 ---------------------------------------------------------------------------------------------------------------------------------------


    /**
     * 加载蜜淘banner图
     * @return
     */
    @GetMapping("/getBeeBanners")
    public ResponseServer getBeeBanners(){
        List<Banners> bannersList = bannersDao.queryBannersByType("1");
        return ResponseServer.success("加载成功", bannersList);
    }


    /**
     * 加载蜜淘推荐的二级分类top7
     * @return
     */
    @GetMapping("/getBeeGoodsCategory")
    public ResponseServer getBeeGoodsCategory(){
        List<GoodsCategory> goodsCategoryList = goodsCategoryDao.queryGoodsCategoryBy2();
        return ResponseServer.success("加载成功", goodsCategoryList);
    }


    /**
     * 加载蜜淘热销产品信息top10
     * @return
     */
    @GetMapping("/getBeeIsHotGoodsInfo")
    public ResponseServer getBeeIsHotGoodsInfo(){
        List<GoodsInfo> goodsInfoList = goodsInfoDao.queryGoodsInfoByIsHot();
        return ResponseServer.success("加载成功", goodsInfoList);
    }


    /**
     * 加载蜜淘所有类别信息
     * @return
     */
    @GetMapping("/getBeeGoodsCategoryInfo")
    public ResponseServer getBeeGoodsCategoryInfo(){
        List<GoodsCategoryVO> goodsCategoryList = goodsCategoryDao.queryGoodsCategoryByAll1();
        if(goodsCategoryList.size() > 0){
            for(GoodsCategoryVO vo : goodsCategoryList){
                vo.setVoList(goodsCategoryDao.queryGoodsCategoryByAll2(vo.getId()));
            }
        }
        return ResponseServer.success("加载成功", goodsCategoryList);
    }


    /**
     * 加载蜜淘所有类别信息
     * @param goodsId
     * @param userId
     * @return
     */
    @GetMapping("/getGoodsInfoDetailsData")
    public ResponseServer getGoodsInfoDetailsData(Integer goodsId, Integer userId){
        GoodsInfo goodsInfo = goodsInfoDao.queryById(goodsId);
        GoodsInfoVO vo = new GoodsInfoVO();
        BeanUtils.copyProperties(goodsInfo, vo);
        if(goodsInfo.getBannerImg().length() > 0){
            String[] strings = goodsInfo.getBannerImg().split(";");
            List list = new ArrayList();
            for(int i = 0; i < strings.length; i++){
                list.add(strings[i]);
            }
            vo.setBannerImgList(list);
        }
        if(goodsInfo.getDetailsImg().length() > 0){
            String[] strings1 = goodsInfo.getDetailsImg().split(";");
            List list1 = new ArrayList();
            for(int y = 0; y < strings1.length; y++){
                list1.add(strings1[y]);
            }
            vo.setDetailsImgList(list1);
        }

        List<SkuSVO> skuSVOList = new ArrayList<>();

        GoodsSkuSelected skuSelected = goodsSkuSelectedDao.queryGoodsSkuSelectedByProductId(goodsId);
        int index = 0;
        if(skuSelected.getSpecAttribute().contains(",")){
            String[] strings = skuSelected.getSpecAttribute().split(",");
            for(int u = 0 ; u < strings.length; u++){
                String str = strings[u];

                SkuSVO skuSVO = new SkuSVO();
                skuSVO.setId(index);

                String[] strings1 = str.split("\\+");
                String specId = strings1[0];

                skuSVO.setProductId(goodsId);
                skuSVO.setSpecId(Integer.parseInt(specId));
                skuSVO.setSpecName(goodsSpecAttributeDao.queryById(Integer.parseInt(specId)).getSpecName());

                List<SkuAVO> list = new ArrayList();

                String attIds = strings1[1];
                if(attIds.contains("_")){
                    String[] strings2 = attIds.split("_");
                    for(int p = 0; p < strings2.length; p++){
                        String attId = strings2[p];

                        SkuAVO skuAVO = new SkuAVO();
                        skuAVO.setArrId(Integer.parseInt(attId));
                        skuAVO.setAttName(goodsSpecAttributeDao.queryById(Integer.parseInt(attId)).getAttributeName());
                        list.add(skuAVO);
                    }
                }else{
                    SkuAVO skuAVO = new SkuAVO();
                    skuAVO.setArrId(Integer.parseInt(attIds));
                    skuAVO.setAttName(goodsSpecAttributeDao.queryById(Integer.parseInt(attIds)).getAttributeName());
                    list.add(skuAVO);
                }
                skuSVO.setSkuAVOList(list);

                skuSVOList.add(skuSVO);

                index++;
            }
        }else{
            String str = skuSelected.getSpecAttribute();

            SkuSVO skuSVO = new SkuSVO();
            skuSVO.setId(index);

            String[] strings1 = str.split("\\+");
            String specId = strings1[0];

            skuSVO.setProductId(goodsId);
            skuSVO.setSpecId(Integer.parseInt(specId));
            skuSVO.setSpecName(goodsSpecAttributeDao.queryById(Integer.parseInt(specId)).getSpecName());

            List<SkuAVO> list = new ArrayList();

            String attIds = strings1[1];
            if(attIds.contains("_")){
                String[] strings2 = attIds.split("_");
                for(int p = 0; p < strings2.length; p++){
                    String attId = strings2[p];

                    SkuAVO skuAVO = new SkuAVO();
                    skuAVO.setArrId(Integer.parseInt(attId));
                    skuAVO.setAttName(goodsSpecAttributeDao.queryById(Integer.parseInt(attId)).getAttributeName());
                    list.add(skuAVO);
                }
            }else{
                SkuAVO skuAVO = new SkuAVO();
                skuAVO.setArrId(Integer.parseInt(attIds));
                skuAVO.setAttName(goodsSpecAttributeDao.queryById(Integer.parseInt(attIds)).getAttributeName());
                list.add(skuAVO);
            }
            skuSVO.setSkuAVOList(list);

            skuSVOList.add(skuSVO);
        }

        vo.setSkuSVOList(skuSVOList);

        List<GoodsSku> skuRelationList = goodsSkuDao.queryByProductId(goodsId);
        vo.setSkuRVOList(skuRelationList);
        Integer quantity = goodsCartDao.queryCartQuantityByUserId(userId);
        vo.setCartQuantity(quantity);
        return ResponseServer.success("加载成功", vo);
    }


    /**
     * 加入购物车
     * @param goodsId
     * @param userId
     * @param skuId
     * @param quantity
     * @return
     */
    @GetMapping("/getBeeSaveGoodsCart")
    public ResponseServer getBeeSaveGoodsCart(Integer goodsId, Integer userId, Integer skuId, Integer quantity){
        GoodsInfo goodsInfo = goodsInfoDao.queryById(goodsId);
        GoodsCart gc = goodsCartDao.queryGoodsCartByIds(userId, goodsId, skuId);
        if(gc == null){
            GoodsCart goodsCart = new GoodsCart();
            goodsCart.setGoodsId(goodsId);
            goodsCart.setCategoryId(goodsInfo.getCategoryId());
            goodsCart.setStoreShopId(goodsInfo.getStoreShopId());
            goodsCart.setUserId(userId);
            goodsCart.setGoodsSkuId(skuId);
            goodsCart.setUpdateTime(new Date());
            goodsCart.setQuantity(quantity);
            goodsCartDao.save(goodsCart);
        }else{
            gc.setQuantity(gc.getQuantity() + quantity);
            goodsCartDao.update(gc);
        }
        return ResponseServer.success("加入购物车成功");
    }


    /**
     * 加载购物车数据
     * @param userId
     * @return
     */
    @GetMapping("/getBeeGoodsCartInfo")
    public ResponseServer getBeeGoodsCartInfo(Integer userId){
        List<GoodsCart> cartList = goodsCartDao.queryGoodsCartByUserId(userId);
        List<GoodsCartDTO> list = new ArrayList();
        if(cartList.size() > 0){
            List<StoreShop> storeList = storeShopDao.queryAll();
            for(int i = 0; i < storeList.size(); i++){
                StoreShop store = storeList.get(i);
                GoodsCartDTO dto = new GoodsCartDTO();
                dto.setStoreShopId(store.getId());
                dto.setStoreShopName(store.getName());
                List<GoodsCartVO> list1 = new ArrayList();
                for(int j = 0; j < cartList.size(); j++){
                    GoodsCart cart = cartList.get(j);
                    if(store.getId().equals(cart.getStoreShopId())){
                        GoodsInfo info = goodsInfoDao.queryById(cart.getGoodsId());
                        GoodsCartVO vo = new GoodsCartVO();
                        vo.setId(cart.getId());
                        vo.setUserId(cart.getUserId());
                        vo.setStoreShopId(cart.getStoreShopId());
                        vo.setCategoryId(info.getCategoryId());
                        vo.setGoodsId(info.getId());
                        vo.setStoreShopId(info.getStoreShopId());
                        vo.setStoreShopName(store.getName());
                        vo.setGoodsImg(info.getImg());
                        vo.setGoodsName(info.getName());
                        vo.setGoodsSkuId(cart.getGoodsSkuId());
                        vo.setQuantity(cart.getQuantity());
                        GoodsSku sku = goodsSkuDao.queryById(cart.getGoodsSkuId());
                        vo.setMinimum(sku.getMinimum());
                        vo.setMaximum(sku.getMaximum());
                        vo.setRetailPrice(sku.getRetailPrice());
                        String str = "";
                        if(sku.getGroupRelation().contains(",")){
                            String[] strings = sku.getGroupRelation().split(",");
                            for(int k = 0; k < strings.length; k++){
                                GoodsSpecAttribute spec = goodsSpecAttributeDao.queryById(Integer.parseInt(strings[k]));
                                str += spec.getAttributeName() + ",";
                            }
                        }else{
                            GoodsSpecAttribute spec = goodsSpecAttributeDao.queryById(Integer.parseInt(sku.getGroupRelation()));
                            str = spec.getAttributeName() + ",";
                        }
                        vo.setSpecAttributeName(str.substring(0, str.length()-1));
                        list1.add(vo);
                    }
                }
                dto.setVoList(list1);
                list.add(dto);
            }
        }
        if(list.size() > 0){
            for(int u = list.size() - 1; u >= 0; u--){
                GoodsCartDTO dto = list.get(u);
                if(dto.getVoList().size() <= 0){
                    list.remove(dto);
                }
            }
        }
        return ResponseServer.success("加入购物车成功", list);
    }


    /**
     * 搜索商品数据
     * @param searchName（二级类名称 or 产品名称）
     * @param sortId    排序值：=1（按照后台indexSort设置从小到大），=2（按价格从小到大），=3（按价格从大到小），=4（按销量从大到小）
     * @param pageIndex 当前页
     * @return
     */
    @GetMapping("/getBeeSearchGoodsInfo")
    public ResponseServer getBeeSearchGoodsInfo(String searchName, Integer sortId, Integer pageIndex){
        Map<String, Object> params = new HashMap<>();
        if("搜索商品".equals(searchName)){
            params.put("searchId", 1);
        }else{
            params.put("searchId", 2);
        }
        params.put("searchName", searchName);
        params.put("sortId", sortId);
        params.put("pageNum", pageIndex);
        params.put("pageSize", 10);
        InitPaging.init(params);
        List<GoodsInfo> goodsInfoList = goodsInfoDao.queryGoodsInfoByConditions(params);
        return ResponseServer.success("加载商品数据成功", new PageInfo<>(goodsInfoList));
    }


    /**
     * 购买时根据个人蜜淘等级进行打折
     * @param userId
     * @return
     */
    @GetMapping("/getDiscountInfo")
    public ResponseServer getDiscountInfo(Integer userId){
        Customer customer = customerDao.queryById(userId);
        double discount = 0.0;
        if("1".equals(customer.getIsActiveCopy2())){
            if(customer.getLevelCopy2Id() == 1){
                discount = 1.0;
            }else if(customer.getLevelCopy2Id() == 2){
                discount = 0.9;
            }else if(customer.getLevelCopy2Id() == 3){
                discount = 0.85;
            }else if(customer.getLevelCopy2Id() == 4){
                discount = 0.8;
            }else if(customer.getLevelCopy2Id() == 5){
                discount = 0.75;
            }else if(customer.getLevelCopy2Id() == 6){
                discount = 0.7;
            }else if(customer.getLevelCopy2Id() == 7){
                discount = 0.0;
            }else{
                return ResponseServer.error("个人蜜淘等级错误");
            }
        }else{
            discount = 1.0;
        }
        return ResponseServer.success("加载打折数据成功", discount);
    }


    /**
     * 加载购买的商品信息
     * @param goodsId
     * @param skuId
     * @param quantity
     * @return
     */
    @GetMapping("/getBuyGoodsInfo")
    public ResponseServer getBuyGoodsInfo(Integer goodsId, Integer skuId, Integer quantity){
        List list = new ArrayList();
        GoodsInfo goodsInfo = goodsInfoDao.queryById(goodsId);
        GoodsInfoDTO dto = new GoodsInfoDTO();
        dto.setGoodsId(goodsInfo.getId());
        dto.setGoodsName(goodsInfo.getName());
        dto.setGoodsImg(goodsInfo.getImg());
        dto.setBuyQuantity(quantity);
        String str = "";
        GoodsSku sku = goodsSkuDao.queryById(skuId);
        if(sku.getGroupRelation().contains(",")){
            String[] strings = sku.getGroupRelation().split(",");
            for(int k = 0; k < strings.length; k++){
                GoodsSpecAttribute spec = goodsSpecAttributeDao.queryById(Integer.parseInt(strings[k]));
                str += spec.getAttributeName() + "，";
            }
        }else{
            GoodsSpecAttribute spec = goodsSpecAttributeDao.queryById(Integer.parseInt(sku.getGroupRelation()));
            str = spec.getAttributeName() + "，";
        }
        dto.setSpecAttributeName(str.substring(0, str.length()-1));
        dto.setBuyPrice(sku.getRetailPrice());
        List<StoreShopFreightVO> voList = storeShopFreightDao.queryStoreShopFreightVOById(goodsInfo.getStoreShopId());
        dto.setStoreShopFreightVOList(voList);
        list.add(dto);
        return ResponseServer.success("加载购买的商品数据成功", list);
    }


    /**
     * 蜜淘商城购买商品，余额支付
     * @param goodsId
     * @param consigneeName
     * @param fullAddress
     * @param consigneePhone
     * @param userId
     * @param freight
     * @param skuId
     * @param buyQuantity
     * @return
     */
    @PostMapping("/bee/amoy/pay/voucher")
    public ResponseServer beeAmoyPayVoucher(@RequestParam(required = false) Integer goodsId,
                                          @RequestParam(required = false) String consigneeName,
                                          @RequestParam(required = false) String fullAddress,
                                          @RequestParam(required = false) String consigneePhone,
                                          @RequestParam(required = false) Integer userId,
                                          @RequestParam(required = false) BigDecimal freight,
                                            @RequestParam(required = false) Integer skuId,
                                            @RequestParam(required = false) Integer buyQuantity){

        System.err.println("-------------创建订单传递的参数：productId= " + goodsId);
        System.err.println("-------------创建订单传递的参数：consigneeName= " + consigneeName);
        System.err.println("-------------创建订单传递的参数：fullAddress= " + fullAddress);
        System.err.println("-------------创建订单传递的参数：consigneePhone= " + consigneePhone);
        System.err.println("-------------创建订单传递的参数：userId= " + userId);
        System.err.println("-------------创建订单传递的参数：freight= " + freight);
        System.err.println("-------------创建订单传递的参数：skuId= " + skuId);
        System.err.println("-------------创建订单传递的参数：buyQuantity= " + buyQuantity);

        GoodsSku sku = goodsSkuDao.queryById(skuId);
        if(sku == null){
            return ResponseServer.error("支付失败,产品SKU错误");
        }
        if(sku.getStock() < buyQuantity){
            return ResponseServer.error("支付失败,产品库存不足");
        }
        // 减少库存
        sku.setStock(sku.getStock() - buyQuantity);
        goodsSkuDao.update(sku);

        GoodsInfo goodsInfo = goodsInfoDao.queryById(goodsId);
        if(goodsInfo == null){
            return ResponseServer.error("支付失败,产品信息错误");
        }
        Customer customer = customerDao.queryById(userId);
        if(customer == null){
            return ResponseServer.error("支付失败,用户信息不正确，请重新授权");
        }

        double discount = 0.0;
        if("1".equals(customer.getIsActiveCopy2())){
            if(customer.getLevelCopy2Id() == 1){
                discount = 1.0;
            }else if(customer.getLevelCopy2Id() == 2){
                discount = 0.9;
            }else if(customer.getLevelCopy2Id() == 3){
                discount = 0.85;
            }else if(customer.getLevelCopy2Id() == 4){
                discount = 0.8;
            }else if(customer.getLevelCopy2Id() == 5){
                discount = 0.75;
            }else if(customer.getLevelCopy2Id() == 6){
                discount = 0.7;
            }else if(customer.getLevelCopy2Id() == 7){
                discount = 0.0;
            }else{
                return ResponseServer.error("个人蜜淘等级错误");
            }
        }else{
            discount = 1.0;
        }

        BigDecimal totalPrice; // 实际支付的钱
        // 商户订单号
        String outTradeNo = "BEE" + Units.getOrderIdByTime().replaceAll("-", "");
        // 交易号
        String tradeNo = "JYH" + Units.getOrderIdByTime().replaceAll("-", "");
        if (freight == null) {
            freight = BigDecimal.valueOf(0.0);
        }

        BigDecimal sumAmount = sku.getRetailPrice().multiply(BigDecimal.valueOf(buyQuantity)); // 没打折之前
        BigDecimal totalAmount = sku.getRetailPrice().multiply(BigDecimal.valueOf(buyQuantity)).multiply(BigDecimal.valueOf(discount)); // 打折后的
        totalPrice = totalAmount.add(freight); // 加运费
        BigDecimal couponAmount = sumAmount.subtract(totalAmount); // 优惠金额
        Account account = accountDao.queryAccountByUserId(userId);
        if(account.getVoucherBalance().doubleValue() < totalPrice.doubleValue()){
            return ResponseServer.error("支付失败,余额不足");
        }
        account.setVoucherBalance(account.getVoucherBalance().subtract(totalPrice));
        int give = (int)Math.round(totalPrice.doubleValue());
        account.setIntegral(account.getIntegral() + give);
        accountDao.update(account);

        AccountRecord ar = new AccountRecord();
        ar.setOutUserId(userId);
        ar.setUpdateTime(new Date());
        ar.setType("0");
        ar.setAmount(totalPrice);
        ar.setNowAmount(account.getVoucherBalance());
        ar.setSign("2");
        ar.setOrderNo(outTradeNo);
        ar.setInfo(customer.getAgentCode() + "购买成功! 消费余额：" + totalPrice);
        accountRecordDao.save(ar);

        AccountRecord ar1 = new AccountRecord();
        ar1.setIntoUserId(customer.getId());
        ar1.setUpdateTime(new Date());
        ar1.setType("1");
        ar1.setAmount(BigDecimal.valueOf(give));
        ar1.setNowAmount(BigDecimal.valueOf(account.getIntegral()));
        ar1.setSign("1");
        ar1.setOrderNo(outTradeNo);
        ar1.setInfo(customer.getAgentCode() + "购买成功! 您获得积分：" + give);
        accountRecordDao.save(ar1);

        Date date = new Date();
        // TODO 创建订单
        GoodsOrders orders = new GoodsOrders();
        orders.setOrderNo(outTradeNo);
        orders.setTotalAmount(totalPrice); // 总支付
        orders.setPayType("1");
        orders.setPrepayId("");
        orders.setOrderPersonId(userId);
        orders.setConsigneeName(consigneeName);
        orders.setConsigneePhone(consigneePhone);
        orders.setAddress(fullAddress);
        orders.setUpdateTime(date);
        goodsOrdersDao.save(orders);

        // TODO 创建交易订单
        GoodsOrderTrades trades = new GoodsOrderTrades();
        trades.setOrderNo(outTradeNo);
        // 交易号
        trades.setTradeNo(tradeNo);
        // 店铺ID
        trades.setStoreShopId(goodsInfo.getStoreShopId());
        // 类别ID
        trades.setCategoryId(goodsInfo.getCategoryId());
        // 下单人
        trades.setOrderPersonId(userId);
        // 支付金额
        trades.setPayAmount(totalPrice);
        // 运费
        trades.setFreight(freight);
        // 优惠金额
        trades.setCouponAmount(couponAmount);
        // 支付状态（0=待支付，1=支付成功，2=支付失败，3=已退款，4=交易关闭）
        trades.setPayStatus("1");
        // 订单处理状态（0=待付款，1=待发货，2=待收货，3=交易成功，4=交易关闭）
        trades.setDealStatus("1");
        // 退款状态（0=未申请退款，1=申请退款，2=退款成功，3=退款失败，4=拒绝退款，5=交易关闭）
        trades.setRefundStatus("0");
        // 更新时间
        trades.setUpdateTime(date);
        // 是否删除(0=否，1=是)
        trades.setIsDel("0");
        trades.setRefundInfo("无");
        trades.setRemarks("无");
        // goodsOrderTradesDao.save(trades);

        // TODO 订单详情
        GoodsOrderDetails details = new GoodsOrderDetails();
        // 交易号
        details.setTradeNo(tradeNo);
        // 店铺ID
        details.setStoreShopId(goodsInfo.getStoreShopId());
        // 店铺名称
        details.setStoreShopName(storeShopDao.queryById(goodsInfo.getStoreShopId()).getName());
        // 类别ID
        details.setCategoryId(goodsInfo.getCategoryId());
        // 类别名称
        details.setCategoryName(goodsCategoryDao.queryById(goodsInfo.getCategoryId()).getName());
        // 商品ID
        details.setGoodsId(goodsInfo.getId());
        // 商品类型
        details.setGoodsType(goodsInfo.getType());
        // 商品图片
        details.setGoodsImg(goodsInfo.getImg());
        // 商品名称
        details.setGoodsName(goodsInfo.getName());
        // 编号
        details.setGoodsCode(goodsInfo.getCode());
        // 商品SKU_ID
        details.setSkuId(sku.getId());
        // 规格属性
        if(sku.getGroupRelation().contains(",")){
            String[] strings = sku.getGroupRelation().split(",");
            String str = "";
            for(int u = 0; u < strings.length; u++){
                str += goodsSpecAttributeDao.queryById(Integer.parseInt(strings[u])).getAttributeName() + "，";
            }
            details.setSpecAttributeName(str.substring(0, str.length()-1));
        }else{
            details.setSpecAttributeName(goodsSpecAttributeDao.queryById(Integer.parseInt(sku.getGroupRelation())).getAttributeName());
        }
        // 购买数量
        details.setQuantity(buyQuantity);
        // 购买时的单价
        details.setUnitPrice(sku.getRetailPrice());
        // 购买时的成本价
        details.setCostPrice(sku.getCostPrice());
        // 更新时间
        details.setUpdateTime(date);
        goodsOrderDetailsDao.save(details);

        trades.setBuyInfo(goodsInfo.getName() + "(" + details.getSpecAttributeName() + " x" + details.getQuantity() + ")");
        goodsOrderTradesDao.save(trades);

        // 添加销量
        goodsInfo.setSales(goodsInfo.getSales() + 1);
        goodsInfoDao.update(goodsInfo);

        // TODO 处理业绩，等级，分润
        // +累计升级
        customer.setAddUpUpgrade(customer.getAddUpUpgrade().add(totalPrice));
        Double addUpUpgrade = customer.getAddUpUpgrade().add(customer.getAddUpUpgradeFiction()).doubleValue(); // 真实累计购买 + 同步等级虚拟金额
        if(addUpUpgrade < 10000){
            if(customer.getLevelCopy2Id() < 2){
                customer.setLevelCopy2Id(2);
                if("0".equals(customer.getIsActiveCopy2())){
                    customer.setIsActiveCopy2("1"); // 激活蜜淘等级
                }
                // 同步共享等级
                customer.setLevelCopyId(2);
                if("0".equals(customer.getIsActiveCopy())){
                    // 是否购买过共享产品
                    List<Orders> ordersList = ordersDao.queryOrdersByUserIdIsBuyShare(customer.getId());
                    if(ordersList.size() > 0){
                        customer.setIsActiveCopy("1"); // 激活共享等级
                    }
                }
                // 同步拼团等级
                customer.setLevelId(2);
                if("0".equals(customer.getIsActive())){
                    // 是否购买过拼团产品
                    List<Orders> ordersList = ordersDao.queryOrdersByUserIdIsBuyCollage(customer.getId());
                    if(ordersList.size() > 0){
                        customer.setIsActive("1"); // 激活拼团等级
                    }
                }
                // TODO 直播等级 等待完善
                // 同步直播等级
                customer.setLevelCopy1Id(2);
                // 判断是否购买过直播产品，买过就激活
                customer.setIsActiveCopy1("0"); // 待激活直播等级
            }
        }else if(addUpUpgrade >= 10000 && addUpUpgrade < 50000){
            if(customer.getLevelCopy2Id() < 3){
                customer.setLevelCopy2Id(3);
                if("0".equals(customer.getIsActiveCopy2())){
                    customer.setIsActiveCopy2("1"); // 激活蜜淘等级
                }
                // 同步共享等级
                customer.setLevelCopyId(3);
                if("0".equals(customer.getIsActiveCopy())){
                    // 是否购买过共享产品
                    List<Orders> ordersList = ordersDao.queryOrdersByUserIdIsBuyShare(customer.getId());
                    if(ordersList.size() > 0){
                        customer.setIsActiveCopy("1"); // 激活共享等级
                    }
                }
                // 同步拼团等级
                customer.setLevelId(3);
                if("0".equals(customer.getIsActive())){
                    // 是否购买过拼团产品
                    List<Orders> ordersList = ordersDao.queryOrdersByUserIdIsBuyCollage(customer.getId());
                    if(ordersList.size() > 0){
                        customer.setIsActive("1"); // 激活拼团等级
                    }
                }
                // TODO 直播等级 等待完善
                // 同步直播等级
                customer.setLevelCopy1Id(3);
                // 判断是否购买过直播产品，买过就激活
                customer.setIsActiveCopy1("0"); // 待激活直播等级
            }
        }else if(addUpUpgrade >= 50000 && addUpUpgrade < 100000){
            if(customer.getLevelCopy2Id() < 4){
                customer.setLevelCopy2Id(4);
                if("0".equals(customer.getIsActiveCopy2())){
                    customer.setIsActiveCopy2("1"); // 激活蜜淘等级
                }
                // 同步共享等级
                customer.setLevelCopyId(4);
                if("0".equals(customer.getIsActiveCopy())){
                    // 是否购买过共享产品
                    List<Orders> ordersList = ordersDao.queryOrdersByUserIdIsBuyShare(customer.getId());
                    if(ordersList.size() > 0){
                        customer.setIsActiveCopy("1"); // 激活共享等级
                    }
                }
                // 同步拼团等级
                customer.setLevelId(4);
                if("0".equals(customer.getIsActive())){
                    // 是否购买过拼团产品
                    List<Orders> ordersList = ordersDao.queryOrdersByUserIdIsBuyCollage(customer.getId());
                    if(ordersList.size() > 0){
                        customer.setIsActive("1"); // 激活拼团等级
                    }
                }
                // TODO 直播等级 等待完善
                // 同步直播等级
                customer.setLevelCopy1Id(4);
                // 判断是否购买过直播产品，买过就激活
                customer.setIsActiveCopy1("0"); // 待激活直播等级
            }
        }else if(addUpUpgrade >= 100000 && addUpUpgrade < 200000){
            if(customer.getLevelCopy2Id() < 5){
                customer.setLevelCopy2Id(5);
                if("0".equals(customer.getIsActiveCopy2())){
                    customer.setIsActiveCopy2("1"); // 激活蜜淘等级
                }
                // 同步共享等级
                customer.setLevelCopyId(5);
                if("0".equals(customer.getIsActiveCopy())){
                    // 是否购买过共享产品
                    List<Orders> ordersList = ordersDao.queryOrdersByUserIdIsBuyShare(customer.getId());
                    if(ordersList.size() > 0){
                        customer.setIsActiveCopy("1"); // 激活共享等级
                    }
                }
                // 同步拼团等级
                customer.setLevelId(5);
                if("0".equals(customer.getIsActive())){
                    // 是否购买过拼团产品
                    List<Orders> ordersList = ordersDao.queryOrdersByUserIdIsBuyCollage(customer.getId());
                    if(ordersList.size() > 0){
                        customer.setIsActive("1"); // 激活拼团等级
                    }
                }
                // TODO 直播等级 等待完善
                // 同步直播等级
                customer.setLevelCopy1Id(5);
                // 判断是否购买过直播产品，买过就激活
                customer.setIsActiveCopy1("0"); // 待激活直播等级
            }
        }else if(addUpUpgrade >= 200000){
            if(customer.getLevelCopy2Id() < 6){
                customer.setLevelCopy2Id(6);
                if("0".equals(customer.getIsActiveCopy2())){
                    customer.setIsActiveCopy2("1"); // 激活蜜淘等级
                }
                // 同步共享等级
                customer.setLevelCopyId(6);
                if("0".equals(customer.getIsActiveCopy())){
                    // 是否购买过共享产品
                    List<Orders> ordersList = ordersDao.queryOrdersByUserIdIsBuyShare(customer.getId());
                    if(ordersList.size() > 0){
                        customer.setIsActiveCopy("1"); // 激活共享等级
                    }
                }
                // 同步拼团等级
                customer.setLevelId(6);
                if("0".equals(customer.getIsActive())){
                    // 是否购买过拼团产品
                    List<Orders> ordersList = ordersDao.queryOrdersByUserIdIsBuyCollage(customer.getId());
                    if(ordersList.size() > 0){
                        customer.setIsActive("1"); // 激活拼团等级
                    }
                }
                // TODO 直播等级 等待完善
                // 同步直播等级
                customer.setLevelCopy1Id(6);
                // 判断是否购买过直播产品，买过就激活
                customer.setIsActiveCopy1("0"); // 待激活直播等级
            }
        }
        customerDao.update(customer);

        // 直推上级
        Customer pCustomer = customerDao.queryById(customer.getParentId());
        if(pCustomer != null) {
            // +累计升级
            pCustomer.setAddUpUpgrade(pCustomer.getAddUpUpgrade().add(totalPrice));
            Double addUpUpgrade_p = pCustomer.getAddUpUpgrade().add(pCustomer.getAddUpUpgradeFiction()).doubleValue();
            if (addUpUpgrade_p < 10000) {
                if (pCustomer.getLevelCopy2Id() < 2) {
                    pCustomer.setLevelCopy2Id(2);
                    if("0".equals(pCustomer.getIsActiveCopy2())){
                        pCustomer.setIsActiveCopy2("1"); // 激活蜜淘等级
                    }
                    // 同步共享等级
                    pCustomer.setLevelCopyId(2);
                    if("0".equals(pCustomer.getIsActiveCopy())){
                        // 是否购买过共享产品
                        List<Orders> ordersList = ordersDao.queryOrdersByUserIdIsBuyShare(pCustomer.getId());
                        if(ordersList.size() > 0){
                            pCustomer.setIsActiveCopy("1"); // 激活共享等级
                        }
                    }
                    // 同步拼团等级
                    pCustomer.setLevelId(2);
                    if("0".equals(pCustomer.getIsActive())){
                        // 是否购买过拼团产品
                        List<Orders> ordersList = ordersDao.queryOrdersByUserIdIsBuyCollage(pCustomer.getId());
                        if(ordersList.size() > 0){
                            pCustomer.setIsActive("1"); // 激活拼团等级
                        }
                    }
                    // TODO 直播等级 等待完善
                    // 同步直播等级
                    pCustomer.setLevelCopy1Id(2);
                    // 判断是否购买过直播产品，买过就激活
                    pCustomer.setIsActiveCopy1("0"); // 待激活直播等级
                }
            } else if (addUpUpgrade_p >= 10000 && addUpUpgrade_p < 50000) {
                if (pCustomer.getLevelCopy2Id() < 3) {
                    pCustomer.setLevelCopy2Id(3);
                    if("0".equals(pCustomer.getIsActiveCopy2())){
                        pCustomer.setIsActiveCopy2("1"); // 激活蜜淘等级
                    }
                    // 同步共享等级
                    pCustomer.setLevelCopyId(3);
                    if("0".equals(pCustomer.getIsActiveCopy())){
                        // 是否购买过共享产品
                        List<Orders> ordersList = ordersDao.queryOrdersByUserIdIsBuyShare(pCustomer.getId());
                        if(ordersList.size() > 0){
                            pCustomer.setIsActiveCopy("1"); // 激活共享等级
                        }
                    }
                    // 同步拼团等级
                    pCustomer.setLevelId(3);
                    if("0".equals(pCustomer.getIsActive())){
                        // 是否购买过拼团产品
                        List<Orders> ordersList = ordersDao.queryOrdersByUserIdIsBuyCollage(pCustomer.getId());
                        if(ordersList.size() > 0){
                            pCustomer.setIsActive("1"); // 激活拼团等级
                        }
                    }
                    // TODO 直播等级 等待完善
                    // 同步直播等级
                    pCustomer.setLevelCopy1Id(3);
                    // 判断是否购买过直播产品，买过就激活
                    pCustomer.setIsActiveCopy1("0"); // 待激活直播等级
                }
            } else if (addUpUpgrade_p >= 50000 && addUpUpgrade_p < 100000) {
                if (pCustomer.getLevelCopy2Id() < 4) {
                    pCustomer.setLevelCopy2Id(4);
                    if("0".equals(pCustomer.getIsActiveCopy2())){
                        pCustomer.setIsActiveCopy2("1"); // 激活蜜淘等级
                    }
                    // 同步共享等级
                    pCustomer.setLevelCopyId(4);
                    if("0".equals(pCustomer.getIsActiveCopy())){
                        // 是否购买过共享产品
                        List<Orders> ordersList = ordersDao.queryOrdersByUserIdIsBuyShare(pCustomer.getId());
                        if(ordersList.size() > 0){
                            pCustomer.setIsActiveCopy("1"); // 激活共享等级
                        }
                    }
                    // 同步拼团等级
                    pCustomer.setLevelId(4);
                    if("0".equals(pCustomer.getIsActive())){
                        // 是否购买过拼团产品
                        List<Orders> ordersList = ordersDao.queryOrdersByUserIdIsBuyCollage(pCustomer.getId());
                        if(ordersList.size() > 0){
                            pCustomer.setIsActive("1"); // 激活拼团等级
                        }
                    }
                    // TODO 直播等级 等待完善
                    // 同步直播等级
                    pCustomer.setLevelCopy1Id(4);
                    // 判断是否购买过直播产品，买过就激活
                    pCustomer.setIsActiveCopy1("0"); // 待激活直播等级
                }
            } else if (addUpUpgrade_p >= 100000 && addUpUpgrade_p < 200000) {
                if (pCustomer.getLevelCopy2Id() < 5) {
                    pCustomer.setLevelCopy2Id(5);
                    if("0".equals(pCustomer.getIsActiveCopy2())){
                        pCustomer.setIsActiveCopy2("1"); // 激活蜜淘等级
                    }
                    // 同步共享等级
                    pCustomer.setLevelCopyId(5);
                    if("0".equals(pCustomer.getIsActiveCopy())){
                        // 是否购买过共享产品
                        List<Orders> ordersList = ordersDao.queryOrdersByUserIdIsBuyShare(pCustomer.getId());
                        if(ordersList.size() > 0){
                            pCustomer.setIsActiveCopy("1"); // 激活共享等级
                        }
                    }
                    // 同步拼团等级
                    pCustomer.setLevelId(5);
                    if("0".equals(pCustomer.getIsActive())){
                        // 是否购买过拼团产品
                        List<Orders> ordersList = ordersDao.queryOrdersByUserIdIsBuyCollage(pCustomer.getId());
                        if(ordersList.size() > 0){
                            pCustomer.setIsActive("1"); // 激活拼团等级
                        }
                    }
                    // TODO 直播等级 等待完善
                    // 同步直播等级
                    pCustomer.setLevelCopy1Id(5);
                    // 判断是否购买过直播产品，买过就激活
                    pCustomer.setIsActiveCopy1("0"); // 待激活直播等级
                }
            } else if (addUpUpgrade_p >= 200000) {
                if (pCustomer.getLevelCopy2Id() < 6) {
                    pCustomer.setLevelCopy2Id(6);
                    if("0".equals(pCustomer.getIsActiveCopy2())){
                        pCustomer.setIsActiveCopy2("1"); // 激活蜜淘等级
                    }
                    // 同步共享等级
                    pCustomer.setLevelCopyId(6);
                    if("0".equals(pCustomer.getIsActiveCopy())){
                        // 是否购买过共享产品
                        List<Orders> ordersList = ordersDao.queryOrdersByUserIdIsBuyShare(pCustomer.getId());
                        if(ordersList.size() > 0){
                            pCustomer.setIsActiveCopy("1"); // 激活共享等级
                        }
                    }
                    // 同步拼团等级
                    pCustomer.setLevelId(6);
                    if("0".equals(pCustomer.getIsActive())){
                        // 是否购买过拼团产品
                        List<Orders> ordersList = ordersDao.queryOrdersByUserIdIsBuyCollage(pCustomer.getId());
                        if(ordersList.size() > 0){
                            pCustomer.setIsActive("1"); // 激活拼团等级
                        }
                    }
                    // TODO 直播等级 等待完善
                    // 同步直播等级
                    pCustomer.setLevelCopy1Id(6);
                    // 判断是否购买过直播产品，买过就激活
                    pCustomer.setIsActiveCopy1("0"); // 待激活直播等级
                }
            }
            customerDao.update(pCustomer);

            // TODO 分账
            GoodsSplitAccount split = new GoodsSplitAccount();
            // 交易号
            split.setTradeNo(tradeNo);
            // 下单人
            split.setOrderPersonId(userId);
            // 占比金额
            split.setSplitAccount(totalAmount);
            // 分给上级ID
            split.setParentId(pCustomer.getId());
            // 分账状态(0=待到账，1=已到账，2=已退款)
            split.setStatus("0");
            // 更新时间
            split.setUpdateTime(date);
            split.setMoney(new BigDecimal(0));
            goodsSplitAccountDao.save(split);

            // 利润50%加入到当日奖池
            Double profit5 = sku.getParentProfit().doubleValue() * 0.5;
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
            String time = sdf.format(new Date());
            GoodsPrizePool app = goodsPrizePoolDao.queryGoodsPrizePoolByToday(time);
            if(app == null){
                // 创建今日奖池
                GoodsPrizePool newApp = new GoodsPrizePool();
                newApp.setPrizePoolAmount(BigDecimal.valueOf(profit5));
                newApp.setUpdateTime(date);
                goodsPrizePoolDao.save(newApp);
            }else{
                // 累计到今日奖池
                app.setPrizePoolAmount(app.getPrizePoolAmount().add(BigDecimal.valueOf(profit5)));
                goodsPrizePoolDao.update(app);
            }
        }
        return ResponseServer.success("余额支付成功!!!");
    }


    /**
     * 加载蜜淘订单数据
     * @param userId
     * @param status
     * @return
     */
    @GetMapping("/getGoodsOrdersData")
    public ResponseServer getGoodsOrdersData(Integer userId, String status){
        List<GoodsOrdersVO> voList = goodsOrdersDao.queryGoodsOrdersVOByStatus(userId, status);
        if(voList.size() > 0){
            for(GoodsOrdersVO vo : voList){
                vo.setDetailsList(goodsOrderDetailsDao.queryByTradeNo(vo.getTradeNo()));
            }
        }
        return ResponseServer.success("加载蜜淘订单数据成功", voList);
    }


    /**
     * 加载蜜淘订单详情数据
     * @param tradeNo
     * @return
     */
    @GetMapping("/getGoodsOrderDetailsData")
    public ResponseServer getGoodsOrderDetailsData(String tradeNo){
        GoodsOrdersVO vo = goodsOrdersDao.queryGoodsOrdersVOByTradeNo(tradeNo);
        vo.setDetailsList(goodsOrderDetailsDao.queryByTradeNo(vo.getTradeNo()));
        return ResponseServer.success("加载蜜淘订单详情数据成功", vo);
    }


    /**
     * 蜜淘订单确定收货
     * @param tradeNo
     * @return
     */
    @PostMapping("/goodsOrdersConfirmReceipt")
    public ResponseServer goodsOrdersConfirmReceipt(String tradeNo){
        GoodsOrderTrades orders = goodsOrderTradesDao.queryByTradeNo(tradeNo);
        if("1".equals(orders.getPayStatus()) && "0".equals(orders.getRefundStatus()) && "2".equals(orders.getDealStatus())){
            orders.setDealStatus("3");
            orders.setConfirmTime(new Date());
            goodsOrderTradesDao.update(orders);
            return ResponseServer.success("确认收货成功");
        }else{
            return ResponseServer.error("确认收货失败，订单状态不正确");
        }
    }


    /**
     * 删除蜜淘订单
     * @param tradeNo
     * @return
     */
    @PostMapping("/deleteGoodsOrders")
    public ResponseServer deleteGoodsOrders(String tradeNo){
        GoodsOrderTrades orders = goodsOrderTradesDao.queryByTradeNo(tradeNo);
        orders.setIsDel("1");
        goodsOrderTradesDao.update(orders);
        return ResponseServer.success();
    }


    /**
     * 蜜淘商城购买商品，微信支付
     * @param request
     * @param goodsId
     * @param consigneeName
     * @param fullAddress
     * @param consigneePhone
     * @param userId
     * @param freight
     * @param skuId
     * @param buyQuantity
     * @return
     * @throws Exception
     */
    @PostMapping("/bee/amoy/pay")
    public ResponseServer beeAmoyPay(HttpServletRequest request, @RequestParam(required = false) Integer goodsId,
                                   @RequestParam(required = false) String consigneeName,
                                   @RequestParam(required = false) String fullAddress,
                                   @RequestParam(required = false) String consigneePhone,
                                   @RequestParam(required = false) Integer userId,
                                   @RequestParam(required = false) BigDecimal freight,
                                   @RequestParam(required = false) Integer skuId,
                                   @RequestParam(required = false) Integer buyQuantity,
                                     @RequestParam(required = false) String openId) throws Exception {

        System.err.println("-------------创建订单传递的参数：productId= " + goodsId);
        System.err.println("-------------创建订单传递的参数：consigneeName= " + consigneeName);
        System.err.println("-------------创建订单传递的参数：fullAddress= " + fullAddress);
        System.err.println("-------------创建订单传递的参数：consigneePhone= " + consigneePhone);
        System.err.println("-------------创建订单传递的参数：userId= " + userId);
        System.err.println("-------------创建订单传递的参数：freight= " + freight);
        System.err.println("-------------创建订单传递的参数：skuId= " + skuId);
        System.err.println("-------------创建订单传递的参数：buyQuantity= " + buyQuantity);

        Map<String, String> maps = new HashMap<>();

        GoodsSku sku = goodsSkuDao.queryById(skuId);
        if(sku == null){
            maps.put("prepayId", "");
            maps.put("msg", "支付失败,产品SKU不正确");
            return ResponseServer.success(maps);
        }
        if(sku.getStock() < buyQuantity){
            maps.put("prepayId", "");
            maps.put("msg", "支付失败,产品库存不足");
            return ResponseServer.success(maps);
        }
        // 减少库存
        sku.setStock(sku.getStock() - buyQuantity);
        goodsSkuDao.update(sku);

        GoodsInfo goodsInfo = goodsInfoDao.queryById(goodsId);
        if(goodsInfo == null){
            maps.put("prepayId", "");
            maps.put("msg", "支付失败,产品信息错误");
            return ResponseServer.success(maps);
        }

        Customer customer = customerDao.queryById(userId);
        if(customer == null){
            maps.put("prepayId", "");
            maps.put("msg", "支付失败,用户信息不正确,请重新授权");
            return ResponseServer.success(maps);
        }

        double discount = 0.0;
        if("1".equals(customer.getIsActiveCopy2())){
            if(customer.getLevelCopy2Id() == 1){
                discount = 1.0;
            }else if(customer.getLevelCopy2Id() == 2){
                discount = 0.9;
            }else if(customer.getLevelCopy2Id() == 3){
                discount = 0.85;
            }else if(customer.getLevelCopy2Id() == 4){
                discount = 0.8;
            }else if(customer.getLevelCopy2Id() == 5){
                discount = 0.75;
            }else if(customer.getLevelCopy2Id() == 6){
                discount = 0.7;
            }else if(customer.getLevelCopy2Id() == 7){
                discount = 0.0;
            }else{
                return ResponseServer.error("个人蜜淘等级错误");
            }
        }else{
            discount = 1.0;
        }

        BigDecimal totalPrice; // 实际支付的钱
        // 商户订单号
        String outTradeNo = "BEE" + Units.getOrderIdByTime().replaceAll("-", "");
        // 交易号
        String tradeNo = "JYH" + Units.getOrderIdByTime().replaceAll("-", "");
        if (freight == null) {
            freight = BigDecimal.valueOf(0.0);
        }

        BigDecimal sumAmount = sku.getRetailPrice().multiply(BigDecimal.valueOf(buyQuantity)); // 没打折之前
        BigDecimal totalAmount = sku.getRetailPrice().multiply(BigDecimal.valueOf(buyQuantity)).multiply(BigDecimal.valueOf(discount)); // 打折后的
        totalPrice = totalAmount.add(freight); // 加运费
        BigDecimal couponAmount = sumAmount.subtract(totalAmount); // 优惠金额

        Map<String, String> map;
        if (totalPrice.doubleValue() > 0) {
            Map<String, Object> wxPay = new HashMap<>();
            wxPay.put("totalPrice", totalPrice.doubleValue());
            wxPay.put("outTradeNo", outTradeNo);
            wxPay.put("openId", openId);
            wxPay.put("notifyUrl", Constants.notify_url_beeAmoy);
            wxPay.put("wxPayAppId", Constants.wxAppId);
            wxPay.put("tradeType", Constants.trade_type);
            String paramBuffer = CreateUnifiedOrder.UnifiedOrder(request, wxPay);
            map = Units.doXMLParse(HttpRequestUtil.sendPost(Constants.pay_url, new String(paramBuffer.getBytes(), "UTF-8")));
            // 创建订单
            if (map != null) {
                Date date = new Date();
                // TODO 创建订单
                GoodsOrders orders = new GoodsOrders();
                orders.setOrderNo(outTradeNo);
                orders.setTotalAmount(totalPrice); // 总支付
                orders.setPayType("0");
                orders.setPrepayId(map.get("prepay_id"));
                orders.setOrderPersonId(userId);
                orders.setConsigneeName(consigneeName);
                orders.setConsigneePhone(consigneePhone);
                orders.setAddress(fullAddress);
                orders.setUpdateTime(date);
                goodsOrdersDao.save(orders);

                // TODO 创建交易订单
                GoodsOrderTrades trades = new GoodsOrderTrades();
                trades.setOrderNo(outTradeNo);
                // 交易号
                trades.setTradeNo(tradeNo);
                // 店铺ID
                trades.setStoreShopId(goodsInfo.getStoreShopId());
                // 类别ID
                trades.setCategoryId(goodsInfo.getCategoryId());
                // 下单人
                trades.setOrderPersonId(userId);
                // 支付金额
                trades.setPayAmount(totalPrice);
                // 运费
                trades.setFreight(freight);
                // 优惠金额
                trades.setCouponAmount(couponAmount);
                // 支付状态（0=待支付，1=支付成功，2=支付失败，3=已退款，4=交易关闭）
                trades.setPayStatus("0");
                // 订单处理状态（0=待付款，1=待发货，2=待收货，3=交易成功，4=交易关闭）
                trades.setDealStatus("0");
                // 退款状态（0=未申请退款，1=申请退款，2=退款成功，3=退款失败，4=拒绝退款，5=交易关闭）
                trades.setRefundStatus("0");
                // 更新时间
                trades.setUpdateTime(date);
                // 是否删除(0=否，1=是)
                trades.setIsDel("1");
                trades.setRefundInfo("无");
                trades.setRemarks("无");
                // goodsOrderTradesDao.save(trades);

                // TODO 订单详情
                GoodsOrderDetails details = new GoodsOrderDetails();
                // 交易号
                details.setTradeNo(tradeNo);
                // 店铺ID
                details.setStoreShopId(goodsInfo.getStoreShopId());
                // 店铺名称
                details.setStoreShopName(storeShopDao.queryById(goodsInfo.getStoreShopId()).getName());
                // 类别ID
                details.setCategoryId(goodsInfo.getCategoryId());
                // 类别名称
                details.setCategoryName(goodsCategoryDao.queryById(goodsInfo.getCategoryId()).getName());
                // 商品ID
                details.setGoodsId(goodsInfo.getId());
                // 商品类型
                details.setGoodsType(goodsInfo.getType());
                // 商品图片
                details.setGoodsImg(goodsInfo.getImg());
                // 商品名称
                details.setGoodsName(goodsInfo.getName());
                // 编号
                details.setGoodsCode(goodsInfo.getCode());
                // 商品SKU_ID
                details.setSkuId(sku.getId());
                // 规格属性
                if(sku.getGroupRelation().contains(",")){
                    String[] strings = sku.getGroupRelation().split(",");
                    String str = "";
                    for(int u = 0; u < strings.length; u++){
                        str += goodsSpecAttributeDao.queryById(Integer.parseInt(strings[u])).getAttributeName() + "，";
                    }
                    details.setSpecAttributeName(str.substring(0, str.length()-1));
                }else{
                    details.setSpecAttributeName(goodsSpecAttributeDao.queryById(Integer.parseInt(sku.getGroupRelation())).getAttributeName());
                }
                // 购买数量
                details.setQuantity(buyQuantity);
                // 购买时的单价
                details.setUnitPrice(sku.getRetailPrice());
                // 购买时的成本价
                details.setCostPrice(sku.getCostPrice());
                // 更新时间
                details.setUpdateTime(date);
                goodsOrderDetailsDao.save(details);

                trades.setBuyInfo(goodsInfo.getName() + "(" + details.getSpecAttributeName() + " x" + details.getQuantity() + ")");
                goodsOrderTradesDao.save(trades);

                maps.put("prepayId", map.get("prepay_id"));
                maps.put("outTradeNo", outTradeNo);
                return ResponseServer.success(maps);
            }
        }
        maps.put("prepayId", "");
        maps.put("msg", "支付失败,请重试");
        return ResponseServer.success(maps);
    }


    /**
     * 蜜淘商城支付成功后回调
     * @param request
     * @param response
     */
    @PostMapping("/notify_url_beeAmoy")
    public void beeAmoyPayCallback(HttpServletRequest request, HttpServletResponse response) {
        System.err.println("微信回调接口方法 start ----------------------------");
        String inputLine = "";
        String notityXml = "";
        try {
            while ((inputLine = request.getReader().readLine()) != null) {
                notityXml += inputLine;
            }
            // 关闭流
            request.getReader().close();
            System.err.println("小程序商城支付回调：" + notityXml);
            // 解析成Map
            Map<String, String> map = Units.doXMLParse(notityXml);
            System.err.println(map);
            // 判断 支付是否成功
            if ("SUCCESS".equals(map.get("result_code"))) {
                System.err.println("微信回调返回是否支付成功：是");
                // 获得 返回的商户订单号
                String outTradeNo = map.get("out_trade_no");
                double totalFee = Double.parseDouble(map.get("total_fee")) / 100;
                System.err.println("微信回调返回商户订单号：" + outTradeNo);
                System.err.println("微信回调返回支付金额：" + totalFee);

                GoodsOrders orders = goodsOrdersDao.queryByOrderNo(outTradeNo);

                GoodsOrderTrades trades = goodsOrderTradesDao.queryByOrderNo_1(outTradeNo); // 单个购买
                // 修改订单状态
                trades.setPayStatus("1");
                trades.setDealStatus("1");
                trades.setIsDel("0");
                goodsOrderTradesDao.update(trades);

                GoodsOrderDetails details = goodsOrderDetailsDao.queryByTradeNo_1(trades.getTradeNo()); // 单个购买
                GoodsInfo goodsInfo = goodsInfoDao.queryById(details.getGoodsId());
                GoodsSku sku = goodsSkuDao.queryById(details.getSkuId());

                Customer customer = customerDao.queryById(orders.getOrderPersonId());

                Account acc = accountDao.queryAccountByUserId(customer.getId());
                int give = (int)Math.round(orders.getTotalAmount().doubleValue());
                acc.setIntegral(acc.getIntegral() + give);
                accountDao.update(acc);

                AccountRecord ar = new AccountRecord();
                ar.setIntoUserId(customer.getId());
                ar.setUpdateTime(orders.getUpdateTime());
                ar.setType("1");
                ar.setAmount(BigDecimal.valueOf(give));
                ar.setNowAmount(BigDecimal.valueOf(acc.getIntegral()));
                ar.setSign("1");
                ar.setOrderNo(outTradeNo);
                ar.setInfo(customer.getAgentCode() + "购买成功! 您获得积分：" + give);
                accountRecordDao.save(ar);

                // 添加销量
                goodsInfo.setSales(goodsInfo.getSales() + 1);
                goodsInfoDao.update(goodsInfo);

                // TODO 处理业绩，等级，分润
                // +累计升级
                customer.setAddUpUpgrade(customer.getAddUpUpgrade().add(orders.getTotalAmount()));
                Double addUpUpgrade = customer.getAddUpUpgrade().add(customer.getAddUpUpgradeFiction()).doubleValue();
                if(addUpUpgrade < 10000){
                    if(customer.getLevelCopy2Id() < 2){
                        customer.setLevelCopy2Id(2);
                        if("0".equals(customer.getIsActiveCopy2())){
                            customer.setIsActiveCopy2("1"); // 激活蜜淘等级
                        }
                        // 同步共享等级
                        customer.setLevelCopyId(2);
                        if("0".equals(customer.getIsActiveCopy())){
                            // 是否购买过共享产品
                            List<Orders> ordersList = ordersDao.queryOrdersByUserIdIsBuyShare(customer.getId());
                            if(ordersList.size() > 0){
                                customer.setIsActiveCopy("1"); // 激活共享等级
                            }
                        }
                        // 同步拼团等级
                        customer.setLevelId(2);
                        if("0".equals(customer.getIsActive())){
                            // 是否购买过拼团产品
                            List<Orders> ordersList = ordersDao.queryOrdersByUserIdIsBuyCollage(customer.getId());
                            if(ordersList.size() > 0){
                                customer.setIsActive("1"); // 激活拼团等级
                            }
                        }
                        // TODO 直播等级 等待完善
                        // 同步直播等级
                        customer.setLevelCopy1Id(2);
                        // 判断是否购买过直播产品，买过就激活
                        customer.setIsActiveCopy1("0"); // 待激活直播等级
                    }
                }else if(addUpUpgrade >= 10000 && addUpUpgrade < 50000){
                    if(customer.getLevelCopy2Id() < 3){
                        customer.setLevelCopy2Id(3);
                        if("0".equals(customer.getIsActiveCopy2())){
                            customer.setIsActiveCopy2("1"); // 激活蜜淘等级
                        }
                        // 同步共享等级
                        customer.setLevelCopyId(3);
                        if("0".equals(customer.getIsActiveCopy())){
                            // 是否购买过共享产品
                            List<Orders> ordersList = ordersDao.queryOrdersByUserIdIsBuyShare(customer.getId());
                            if(ordersList.size() > 0){
                                customer.setIsActiveCopy("1"); // 激活共享等级
                            }
                        }
                        // 同步拼团等级
                        customer.setLevelId(3);
                        if("0".equals(customer.getIsActive())){
                            // 是否购买过拼团产品
                            List<Orders> ordersList = ordersDao.queryOrdersByUserIdIsBuyCollage(customer.getId());
                            if(ordersList.size() > 0){
                                customer.setIsActive("1"); // 激活拼团等级
                            }
                        }
                        // TODO 直播等级 等待完善
                        // 同步直播等级
                        customer.setLevelCopy1Id(3);
                        // 判断是否购买过直播产品，买过就激活
                        customer.setIsActiveCopy1("0"); // 待激活直播等级
                    }
                }else if(addUpUpgrade >= 50000 && addUpUpgrade < 100000){
                    if(customer.getLevelCopy2Id() < 4){
                        customer.setLevelCopy2Id(4);
                        if("0".equals(customer.getIsActiveCopy2())){
                            customer.setIsActiveCopy2("1"); // 激活蜜淘等级
                        }
                        // 同步共享等级
                        customer.setLevelCopyId(4);
                        if("0".equals(customer.getIsActiveCopy())){
                            // 是否购买过共享产品
                            List<Orders> ordersList = ordersDao.queryOrdersByUserIdIsBuyShare(customer.getId());
                            if(ordersList.size() > 0){
                                customer.setIsActiveCopy("1"); // 激活共享等级
                            }
                        }
                        // 同步拼团等级
                        customer.setLevelId(4);
                        if("0".equals(customer.getIsActive())){
                            // 是否购买过拼团产品
                            List<Orders> ordersList = ordersDao.queryOrdersByUserIdIsBuyCollage(customer.getId());
                            if(ordersList.size() > 0){
                                customer.setIsActive("1"); // 激活拼团等级
                            }
                        }
                        // TODO 直播等级 等待完善
                        // 同步直播等级
                        customer.setLevelCopy1Id(4);
                        // 判断是否购买过直播产品，买过就激活
                        customer.setIsActiveCopy1("0"); // 待激活直播等级
                    }
                }else if(addUpUpgrade >= 100000 && addUpUpgrade < 200000){
                    if(customer.getLevelCopy2Id() < 5){
                        customer.setLevelCopy2Id(5);
                        if("0".equals(customer.getIsActiveCopy2())){
                            customer.setIsActiveCopy2("1"); // 激活蜜淘等级
                        }
                        // 同步共享等级
                        customer.setLevelCopyId(5);
                        if("0".equals(customer.getIsActiveCopy())){
                            // 是否购买过共享产品
                            List<Orders> ordersList = ordersDao.queryOrdersByUserIdIsBuyShare(customer.getId());
                            if(ordersList.size() > 0){
                                customer.setIsActiveCopy("1"); // 激活共享等级
                            }
                        }
                        // 同步拼团等级
                        customer.setLevelId(5);
                        if("0".equals(customer.getIsActive())){
                            // 是否购买过拼团产品
                            List<Orders> ordersList = ordersDao.queryOrdersByUserIdIsBuyCollage(customer.getId());
                            if(ordersList.size() > 0){
                                customer.setIsActive("1"); // 激活拼团等级
                            }
                        }
                        // TODO 直播等级 等待完善
                        // 同步直播等级
                        customer.setLevelCopy1Id(5);
                        // 判断是否购买过直播产品，买过就激活
                        customer.setIsActiveCopy1("0"); // 待激活直播等级
                    }
                }else if(addUpUpgrade >= 200000){
                    if(customer.getLevelCopy2Id() < 6){
                        customer.setLevelCopy2Id(6);
                        if("0".equals(customer.getIsActiveCopy2())){
                            customer.setIsActiveCopy2("1"); // 激活蜜淘等级
                        }
                        // 同步共享等级
                        customer.setLevelCopyId(6);
                        if("0".equals(customer.getIsActiveCopy())){
                            // 是否购买过共享产品
                            List<Orders> ordersList = ordersDao.queryOrdersByUserIdIsBuyShare(customer.getId());
                            if(ordersList.size() > 0){
                                customer.setIsActiveCopy("1"); // 激活共享等级
                            }
                        }
                        // 同步拼团等级
                        customer.setLevelId(6);
                        if("0".equals(customer.getIsActive())){
                            // 是否购买过拼团产品
                            List<Orders> ordersList = ordersDao.queryOrdersByUserIdIsBuyCollage(customer.getId());
                            if(ordersList.size() > 0){
                                customer.setIsActive("1"); // 激活拼团等级
                            }
                        }
                        // TODO 直播等级 等待完善
                        // 同步直播等级
                        customer.setLevelCopy1Id(6);
                        // 判断是否购买过直播产品，买过就激活
                        customer.setIsActiveCopy1("0"); // 待激活直播等级
                    }
                }
                customerDao.update(customer);

                // 直推上级
                Customer pCustomer = customerDao.queryById(customer.getParentId());
                if(pCustomer != null) {
                    // +累计升级
                    pCustomer.setAddUpUpgrade(pCustomer.getAddUpUpgrade().add(orders.getTotalAmount()));
                    Double addUpUpgrade_p = pCustomer.getAddUpUpgrade().add(pCustomer.getAddUpUpgradeFiction()).doubleValue();
                    if (addUpUpgrade_p < 10000) {
                        if (pCustomer.getLevelCopy2Id() < 2) {
                            pCustomer.setLevelCopy2Id(2);
                            if("0".equals(pCustomer.getIsActiveCopy2())){
                                pCustomer.setIsActiveCopy2("1"); // 激活蜜淘等级
                            }
                            // 同步共享等级
                            pCustomer.setLevelCopyId(2);
                            if("0".equals(pCustomer.getIsActiveCopy())){
                                // 是否购买过共享产品
                                List<Orders> ordersList = ordersDao.queryOrdersByUserIdIsBuyShare(pCustomer.getId());
                                if(ordersList.size() > 0){
                                    pCustomer.setIsActiveCopy("1"); // 激活共享等级
                                }
                            }
                            // 同步拼团等级
                            pCustomer.setLevelId(2);
                            if("0".equals(pCustomer.getIsActive())){
                                // 是否购买过拼团产品
                                List<Orders> ordersList = ordersDao.queryOrdersByUserIdIsBuyCollage(pCustomer.getId());
                                if(ordersList.size() > 0){
                                    pCustomer.setIsActive("1"); // 激活拼团等级
                                }
                            }
                            // TODO 直播等级 等待完善
                            // 同步直播等级
                            pCustomer.setLevelCopy1Id(2);
                            // 判断是否购买过直播产品，买过就激活
                            pCustomer.setIsActiveCopy1("0"); // 待激活直播等级
                        }
                    } else if (addUpUpgrade_p >= 10000 && addUpUpgrade_p < 50000) {
                        if (pCustomer.getLevelCopy2Id() < 3) {
                            pCustomer.setLevelCopy2Id(3);
                            if("0".equals(pCustomer.getIsActiveCopy2())){
                                pCustomer.setIsActiveCopy2("1"); // 激活蜜淘等级
                            }
                            // 同步共享等级
                            pCustomer.setLevelCopyId(3);
                            if("0".equals(pCustomer.getIsActiveCopy())){
                                // 是否购买过共享产品
                                List<Orders> ordersList = ordersDao.queryOrdersByUserIdIsBuyShare(pCustomer.getId());
                                if(ordersList.size() > 0){
                                    pCustomer.setIsActiveCopy("1"); // 激活共享等级
                                }
                            }
                            // 同步拼团等级
                            pCustomer.setLevelId(3);
                            if("0".equals(pCustomer.getIsActive())){
                                // 是否购买过拼团产品
                                List<Orders> ordersList = ordersDao.queryOrdersByUserIdIsBuyCollage(pCustomer.getId());
                                if(ordersList.size() > 0){
                                    pCustomer.setIsActive("1"); // 激活拼团等级
                                }
                            }
                            // TODO 直播等级 等待完善
                            // 同步直播等级
                            pCustomer.setLevelCopy1Id(3);
                            // 判断是否购买过直播产品，买过就激活
                            pCustomer.setIsActiveCopy1("0"); // 待激活直播等级
                        }
                    } else if (addUpUpgrade_p >= 50000 && addUpUpgrade_p < 100000) {
                        if (pCustomer.getLevelCopy2Id() < 4) {
                            pCustomer.setLevelCopy2Id(4);
                            if("0".equals(pCustomer.getIsActiveCopy2())){
                                pCustomer.setIsActiveCopy2("1"); // 激活蜜淘等级
                            }
                            // 同步共享等级
                            pCustomer.setLevelCopyId(4);
                            if("0".equals(pCustomer.getIsActiveCopy())){
                                // 是否购买过共享产品
                                List<Orders> ordersList = ordersDao.queryOrdersByUserIdIsBuyShare(pCustomer.getId());
                                if(ordersList.size() > 0){
                                    pCustomer.setIsActiveCopy("1"); // 激活共享等级
                                }
                            }
                            // 同步拼团等级
                            pCustomer.setLevelId(4);
                            if("0".equals(pCustomer.getIsActive())){
                                // 是否购买过拼团产品
                                List<Orders> ordersList = ordersDao.queryOrdersByUserIdIsBuyCollage(pCustomer.getId());
                                if(ordersList.size() > 0){
                                    pCustomer.setIsActive("1"); // 激活拼团等级
                                }
                            }
                            // TODO 直播等级 等待完善
                            // 同步直播等级
                            pCustomer.setLevelCopy1Id(4);
                            // 判断是否购买过直播产品，买过就激活
                            pCustomer.setIsActiveCopy1("0"); // 待激活直播等级
                        }
                    } else if (addUpUpgrade_p >= 100000 && addUpUpgrade_p < 200000) {
                        if (pCustomer.getLevelCopy2Id() < 5) {
                            pCustomer.setLevelCopy2Id(5);
                            if("0".equals(pCustomer.getIsActiveCopy2())){
                                pCustomer.setIsActiveCopy2("1"); // 激活蜜淘等级
                            }
                            // 同步共享等级
                            pCustomer.setLevelCopyId(5);
                            if("0".equals(pCustomer.getIsActiveCopy())){
                                // 是否购买过共享产品
                                List<Orders> ordersList = ordersDao.queryOrdersByUserIdIsBuyShare(pCustomer.getId());
                                if(ordersList.size() > 0){
                                    pCustomer.setIsActiveCopy("1"); // 激活共享等级
                                }
                            }
                            // 同步拼团等级
                            pCustomer.setLevelId(5);
                            if("0".equals(pCustomer.getIsActive())){
                                // 是否购买过拼团产品
                                List<Orders> ordersList = ordersDao.queryOrdersByUserIdIsBuyCollage(pCustomer.getId());
                                if(ordersList.size() > 0){
                                    pCustomer.setIsActive("1"); // 激活拼团等级
                                }
                            }
                            // TODO 直播等级 等待完善
                            // 同步直播等级
                            pCustomer.setLevelCopy1Id(5);
                            // 判断是否购买过直播产品，买过就激活
                            pCustomer.setIsActiveCopy1("0"); // 待激活直播等级
                        }
                    } else if (addUpUpgrade_p >= 200000) {
                        if (pCustomer.getLevelCopy2Id() < 6) {
                            pCustomer.setLevelCopy2Id(6);
                            if("0".equals(pCustomer.getIsActiveCopy2())){
                                pCustomer.setIsActiveCopy2("1"); // 激活蜜淘等级
                            }
                            // 同步共享等级
                            pCustomer.setLevelCopyId(6);
                            if("0".equals(pCustomer.getIsActiveCopy())){
                                // 是否购买过共享产品
                                List<Orders> ordersList = ordersDao.queryOrdersByUserIdIsBuyShare(pCustomer.getId());
                                if(ordersList.size() > 0){
                                    pCustomer.setIsActiveCopy("1"); // 激活共享等级
                                }
                            }
                            // 同步拼团等级
                            pCustomer.setLevelId(6);
                            if("0".equals(pCustomer.getIsActive())){
                                // 是否购买过拼团产品
                                List<Orders> ordersList = ordersDao.queryOrdersByUserIdIsBuyCollage(pCustomer.getId());
                                if(ordersList.size() > 0){
                                    pCustomer.setIsActive("1"); // 激活拼团等级
                                }
                            }
                            // TODO 直播等级 等待完善
                            // 同步直播等级
                            pCustomer.setLevelCopy1Id(6);
                            // 判断是否购买过直播产品，买过就激活
                            pCustomer.setIsActiveCopy1("0"); // 待激活直播等级
                        }
                    }
                    customerDao.update(pCustomer);

                    // TODO 分账
                    GoodsSplitAccount split = new GoodsSplitAccount();
                    // 交易号
                    split.setTradeNo(trades.getTradeNo());
                    // 下单人
                    split.setOrderPersonId(orders.getOrderPersonId());
                    // 占比金额
                    split.setSplitAccount(orders.getTotalAmount());
                    // 分给上级ID
                    split.setParentId(pCustomer.getId());
                    // 分账状态(0=待到账，1=已到账，2=已退款)
                    split.setStatus("0");
                    // 更新时间
                    split.setUpdateTime(orders.getUpdateTime());
                    split.setMoney(new BigDecimal(0));
                    goodsSplitAccountDao.save(split);

                    // 利润50%加入到当日奖池
                    Double profit5 = sku.getParentProfit().doubleValue() * 0.5;
                    SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
                    String time = sdf.format(new Date());
                    GoodsPrizePool app = goodsPrizePoolDao.queryGoodsPrizePoolByToday(time);
                    if(app == null){
                        // 创建今日奖池
                        GoodsPrizePool newApp = new GoodsPrizePool();
                        newApp.setPrizePoolAmount(BigDecimal.valueOf(profit5));
                        newApp.setUpdateTime(orders.getUpdateTime());
                        goodsPrizePoolDao.save(newApp);
                    }else{
                        // 累计到今日奖池
                        app.setPrizePoolAmount(app.getPrizePoolAmount().add(BigDecimal.valueOf(profit5)));
                        goodsPrizePoolDao.update(app);
                    }
                }

                // 封装 返回值
                StringBuffer buffer = new StringBuffer();
                buffer.append("<xml>");
                buffer.append("<return_code>SUCCESS</return_code>");
                buffer.append("<return_msg>OK</return_msg>");
                buffer.append("</xml>");
                // 给微信服务器返回 成功标示 否则会一直询问服务器是否回调成功
                PrintWriter writer = response.getWriter();
                // 返回
                writer.print(buffer.toString());
            }
        } catch (IOException e) {
            e.printStackTrace();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }


    /**
     * 蜜淘商城未支付成功删除订单
     * @param orderNo
     * @return
     */
    @PostMapping("/bee/amoy/deleteGoodsOrders") // 针对详情中购买
    public ResponseServer beeAmoyDeleteGoodsOrders(String orderNo){
        GoodsOrders orders = goodsOrdersDao.queryByOrderNo(orderNo);
        if(orders != null){
            List<GoodsOrderTrades> tradesList = goodsOrderTradesDao.queryByOrderNo(orderNo);
            if(tradesList.size() > 0){
                for(GoodsOrderTrades trades : tradesList){
                    List<GoodsOrderDetails> detailsList = goodsOrderDetailsDao.queryByTradeNo(trades.getTradeNo());
                    if(detailsList.size() > 0){
                        for(GoodsOrderDetails details : detailsList){
                            // 补回库存
                            GoodsSku sku = goodsSkuDao.queryById(details.getSkuId());
                            sku.setStock(sku.getStock() + details.getQuantity());
                            goodsSkuDao.update(sku);
                            goodsOrderDetailsDao.delete(details.getId());
                        }
                    }
                    goodsOrderTradesDao.delete(trades.getId());
                }
            }
            goodsOrdersDao.delete(orders.getId());
        }
        return ResponseServer.success();
    }


    @Autowired
    private BannersDao bannersDao;

    @Autowired
    private GoodsInfoDao goodsInfoDao;

    @Autowired
    private GoodsCategoryDao goodsCategoryDao;

    @Autowired
    private GoodsSkuDao goodsSkuDao;

    @Autowired
    private GoodsCartDao goodsCartDao;

    @Autowired
    private GoodsSpecAttributeDao goodsSpecAttributeDao;

    @Autowired
    private GoodsOrdersDao goodsOrdersDao;

    @Autowired
    private GoodsOrderTradesDao goodsOrderTradesDao;

    @Autowired
    private GoodsOrderDetailsDao goodsOrderDetailsDao;

    @Autowired
    private GoodsSkuSelectedDao goodsSkuSelectedDao;

    @Autowired
    private StoreShopFreightDao storeShopFreightDao;

    @Autowired
    private GoodsPrizePoolDao goodsPrizePoolDao;

    @Autowired
    private GoodsSplitAccountDao goodsSplitAccountDao;


    // TODO 蜜淘商城 ---------------------------------------------------------------------------------------------------------------------------------------


    /**
     * 购买盲盒后的处理 分券 - 本地运行这个方法
     * 2021-07-19 20:32
     * @return
     */
    @GetMapping("/buyBlindBoxAfterHandle")
    public ResponseServer buyBlindBoxAfterHandle(){
        List<Orders> ordersList = ordersDao.queryByBuyBlindBoxAfterHandle();
        System.err.println("一共有" + ordersList.size() + "条数据");
        if(ordersList.size() > 0){
            for(Orders orders : ordersList){
                String outTradeNo = orders.getTradeNo();
                Customer customer = customerDao.queryById(orders.getOrderPersonId());
                if(customer != null){
                    customer.setQuantityRecord(customer.getQuantityRecord() + 1); // 自己累积一次购买盲盒记录
                    customerDao.update(customer);

                    // 赠送拼团券
                    UserCoupon userCoupon = userCouponDao.queryByUserIdAndCouponId(orders.getOrderPersonId(), 1); //拼团券
                    if(userCoupon != null){
                        userCoupon.setQuantity(userCoupon.getQuantity() + 1); // 累加
                        userCouponDao.update(userCoupon);

                        AccountRecord ar1 = new AccountRecord();
                        ar1.setIntoUserId(orders.getOrderPersonId());
                        ar1.setUpdateTime(new Date());
                        ar1.setType("5");
                        ar1.setAmount(new BigDecimal(1));
                        ar1.setNowAmount(new BigDecimal(userCoupon.getQuantity()));
                        ar1.setSign("1");
                        ar1.setOrderNo(outTradeNo);
                        ar1.setInfo(customerDao.queryById(orders.getOrderPersonId()).getAgentCode() + "购买成功! 您获得拼团券：" + 1);
                        accountRecordDao.save(ar1);
                    }else{
                        UserCoupon newUC = new UserCoupon(); // 创建
                        newUC.setQuantity(1);
                        newUC.setUserId(orders.getOrderPersonId());
                        newUC.setCouponId(1);
                        newUC.setUpdateTime(new Date());
                        userCouponDao.save(newUC);

                        AccountRecord ar2 = new AccountRecord();
                        ar2.setIntoUserId(orders.getOrderPersonId());
                        ar2.setUpdateTime(new Date());
                        ar2.setType("5");
                        ar2.setAmount(new BigDecimal(1));
                        ar2.setNowAmount(new BigDecimal(newUC.getQuantity()));
                        ar2.setSign("1");
                        ar2.setOrderNo(outTradeNo);
                        ar2.setInfo(customerDao.queryById(orders.getOrderPersonId()).getAgentCode() + "购买成功! 您获得拼团券：" + 1);
                        accountRecordDao.save(ar2);
                    }

                    // 赠送共享券，赠送等额的积分
                    Account acc = accountDao.queryAccountByUserId(customer.getId());
                    int give = (int)Math.round(orders.getPayAmount().doubleValue());
                    acc.setIntegral(acc.getIntegral() + give); // 返等额积分
                    accountDao.update(acc);

                    AccountRecord ar = new AccountRecord();
                    ar.setIntoUserId(customer.getId());
                    ar.setUpdateTime(new Date());
                    ar.setType("1");
                    ar.setAmount(BigDecimal.valueOf(give));
                    ar.setNowAmount(BigDecimal.valueOf(acc.getIntegral()));
                    ar.setSign("1");
                    ar.setOrderNo(outTradeNo);
                    ar.setInfo(customerDao.queryById(orders.getOrderPersonId()).getAgentCode() + "购买成功! 您获得积分：" + give);
                    accountRecordDao.save(ar);

                    if(customer.getParentId() != null && customer.getParentId() != 1198){
                        Customer parentCustomer = customerDao.queryById(customer.getParentId());
                        if(parentCustomer != null){

                            // 统计下级一共购买的数量
                            int sumQuantity = customerDao.queryBySumQuantityRecord(parentCustomer.getId());

                            if(sumQuantity % 9 == 0){

                                UserCoupon puc = userCouponDao.queryByUserIdAndCouponId(parentCustomer.getId(), 2); //共享券
                                if(puc != null){
                                    puc.setQuantity(puc.getQuantity() + 1); // 累加共享券
                                    userCouponDao.update(puc);

                                    AccountRecord ar3 = new AccountRecord();
                                    ar3.setIntoUserId(parentCustomer.getId());
                                    ar3.setUpdateTime(new Date());
                                    ar3.setType("6");
                                    ar3.setAmount(new BigDecimal(1));
                                    ar3.setNowAmount(new BigDecimal(puc.getQuantity()));
                                    ar3.setSign("1");
                                    ar3.setOrderNo(outTradeNo);
                                    ar3.setInfo(customerDao.queryById(orders.getOrderPersonId()).getAgentCode() + "购买成功! 直推人员累计购买超过9次,您获得共享券：" + 1);
                                    accountRecordDao.save(ar3);
                                }else{
                                    UserCoupon newPUC = new UserCoupon(); // 创建共享券
                                    newPUC.setQuantity(1);
                                    newPUC.setUserId(parentCustomer.getId());
                                    newPUC.setCouponId(2);
                                    newPUC.setUpdateTime(new Date());
                                    userCouponDao.save(newPUC);

                                    AccountRecord ar4 = new AccountRecord();
                                    ar4.setIntoUserId(parentCustomer.getId());
                                    ar4.setUpdateTime(new Date());
                                    ar4.setType("6");
                                    ar4.setAmount(new BigDecimal(1));
                                    ar4.setNowAmount(new BigDecimal(newPUC.getQuantity()));
                                    ar4.setSign("1");
                                    ar4.setOrderNo(outTradeNo);
                                    ar4.setInfo(customerDao.queryById(orders.getOrderPersonId()).getAgentCode() + "购买成功! 直推人员累计购买超过9次,您获得共享券：" + 1);
                                    accountRecordDao.save(ar4);
                                }
                            }
                        }
                    }
                    System.err.println("---------- 结束 ----------");
                }
            }
        }

        return ResponseServer.success();
    }


    /**
     * 购买礼包后的处理 业绩 - 本地运行这个方法
     * 2021-07-19 20:32
     * @return
     */
    @GetMapping("/buyShareAfterHandle")
    public ResponseServer buyShareAfterHandle(){
        List<Orders> ordersList = ordersDao.queryByShareAfterHandle();
        System.err.println("一共有" + ordersList.size() + "条数据");
        if(ordersList.size() > 0){
            for(Orders orders : ordersList){
                Customer customer = customerDao.queryById(orders.getOrderPersonId());
                if(customer != null){
                    customer.setOwnTotalBuy(customer.getOwnTotalBuy().add(orders.getTotalAmount()));
                    customerDao.update(customer);
                    System.err.println("---------- 加业绩 ----------" + orders.getTotalAmount());
                }
            }
        }
        System.err.println("---------- 结束 ----------");
        return ResponseServer.success();
    }


    // 测试
    @GetMapping("/ceshi")
    public ResponseServer ceshi(){
        List<Customer> successList = new ArrayList<>();
        List<Customer> errorList = new ArrayList<>();
        List<Customer> cList = customerDao.queryAll1();
        if(cList.size() > 0){
            for(Customer cu : cList){
                try {
                    if("0".equals(cu.getFiction())){
                        successList.add(cu);
                    }else{
                        // 不等于的0的就会报错，然后怎么在catch中将cu加入到errorList中
                        throw new Exception();
                    }
                }catch (Exception e){
                    errorList.add(cu);
                }
            }
        }
        Map map = new HashMap();
        map.put("successList", successList);
        map.put("errorList", errorList);
        return ResponseServer.success(map);

    }


    /**
     * 同步等级 - 本地运行这个方法
     * @return
     */
    @GetMapping("/synchronizationLevel")
    public ResponseServer synchronizationLevel(){
        List<Customer> customerList = customerDao.queryAll2();
        int rows = customerList.size();
        if(rows > 0){
            for(int i = 0; i < rows; i++){
                Customer customer = customerList.get(i);
                System.err.println("---------->  " + i);
                if(customer.getLevelId() > customer.getLevelCopyId()){
                    // 根据拼团等级 进行同步
                    List<Orders> ordersList = ordersDao.queryOrdersByUserIdIsBuyCollage(customer.getId());
                    if(ordersList.size() > 0){
                        customer.setIsActive("1"); // 激活拼团等级
                    }else{
                        customer.setIsActive("0");
                    }
                    // 共享等级
                    customer.setLevelCopyId(customer.getLevelId());
                    List<Orders> ordersList1 = ordersDao.queryOrdersByUserIdIsBuyShare(customer.getId());
                    if(ordersList1.size() > 0){
                        customer.setIsActiveCopy("1"); // 激活共享等级
                    }else{
                        customer.setIsActiveCopy("0");
                    }
                    // TODO 直播等级 等待完善
                    // 直播等级
                    customer.setLevelCopy1Id(customer.getLevelId());
                    customer.setIsActiveCopy1("0"); // 未激活

                    // 同步蜜淘等级
                    customer.setLevelCopy2Id(customer.getLevelId());
                    if("0".equals(customer.getIsActiveCopy2())){
                        // 是否购买过蜜淘产品
                        List<GoodsOrders> ordersList2 = goodsOrdersDao.queryGoodsOrdersByUserIdIsBuyBeeAmoy(customer.getId());
                        if(ordersList2.size() > 0){
                            customer.setIsActive("1"); // 激活蜜淘等级
                        }
                    }

                    customerDao.update(customer);
                }else if(customer.getLevelId() == customer.getLevelCopyId()){
                    List<Orders> ordersList = ordersDao.queryOrdersByUserIdIsBuyCollage(customer.getId());
                    if(ordersList.size() > 0){
                        customer.setIsActive("1"); // 激活拼团等级
                    }else{
                        customer.setIsActive("0");
                    }
                    List<Orders> ordersList1 = ordersDao.queryOrdersByUserIdIsBuyShare(customer.getId());
                    if(ordersList1.size() > 0){
                        customer.setIsActiveCopy("1"); // 激活共享等级
                    }else{
                        customer.setIsActiveCopy("0");
                    }
                    // TODO 直播等级 等待完善
                    // 直播等级
                    customer.setLevelCopy1Id(customer.getLevelCopyId());
                    customer.setIsActiveCopy1("0"); // 未激活

                    // 同步蜜淘等级
                    customer.setLevelCopy2Id(customer.getLevelCopyId());
                    if("0".equals(customer.getIsActiveCopy2())){
                        // 是否购买过蜜淘产品
                        List<GoodsOrders> ordersList2 = goodsOrdersDao.queryGoodsOrdersByUserIdIsBuyBeeAmoy(customer.getId());
                        if(ordersList2.size() > 0){
                            customer.setIsActive("1"); // 激活蜜淘等级
                        }
                    }

                    customerDao.update(customer);
                }else{
                    // 根据共享等级 进行同步
                    List<Orders> ordersList1 = ordersDao.queryOrdersByUserIdIsBuyShare(customer.getId());
                    if(ordersList1.size() > 0){
                        customer.setIsActiveCopy("1"); // 激活共享等级
                    }else{
                        customer.setIsActiveCopy("0");
                    }
                    // 拼团等级
                    customer.setLevelId(customer.getLevelCopyId());
                    List<Orders> ordersList = ordersDao.queryOrdersByUserIdIsBuyCollage(customer.getId());
                    if(ordersList.size() > 0){
                        customer.setIsActive("1"); // 激活拼团等级
                    }else{
                        customer.setIsActive("0");
                    }
                    // TODO 直播等级 等待完善
                    // 直播等级
                    customer.setLevelCopy1Id(customer.getLevelCopyId());
                    customer.setIsActiveCopy1("0"); // 未激活

                    // 同步蜜淘等级
                    customer.setLevelCopy2Id(customer.getLevelCopyId());
                    if("0".equals(customer.getIsActiveCopy2())){
                        // 是否购买过蜜淘产品
                        List<GoodsOrders> ordersList2 = goodsOrdersDao.queryGoodsOrdersByUserIdIsBuyBeeAmoy(customer.getId());
                        if(ordersList2.size() > 0){
                            customer.setIsActive("1"); // 激活蜜淘等级
                        }
                    }

                    customerDao.update(customer);
                }
            }
        }

        return ResponseServer.success("同步等级成功");
    }


    /**
     * 速度与激情退款 - 本地运行这个方法
     * @return
     */
    @GetMapping("/refund")
    public ResponseServer refund(){
        List<Orders> ordersList = ordersDao.queryOrdersByMode20();
        if(ordersList.size() > 0){
            for(Orders orders : ordersList){
                Account account = accountDao.queryAccountByUserId(orders.getOrderPersonId());
                account.setVoucherBalance(account.getVoucherBalance().add(orders.getTotalAmount()));
                accountDao.update(account);
                AccountRecord ar = new AccountRecord();
                ar.setIntoUserId(orders.getOrderPersonId());
                ar.setUpdateTime(new Date());
                ar.setType("0");
                ar.setAmount(orders.getTotalAmount());
                ar.setNowAmount(account.getVoucherBalance());
                ar.setSign("1");
                ar.setOrderNo(orders.getOrderNo());
                ar.setInfo("系统退回余额：" + orders.getTotalAmount());
                accountRecordDao.save(ar);
                orders.setPayStatus("3");
                orders.setDealStatus("4");
                orders.setRefundStatus("2");
                ordersDao.update(orders);
                System.out.println("OK!!!");
            }
        }
        return ResponseServer.success();
    }


}
